AhmadLang / Java, How To Program, 2004
.pdf
Figure 26.8. HTML document in which the form's action invokes
WelcomeServlet tHRough the alias welcome1 specified in web.xml.
(This item is displayed on page 1250 in the print version)
1 |
<?xml version = "1.0"?> |
2 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" |
3 |
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> |
4 |
|
5 |
<!-- Fig. 26.7: WelcomeServlet.html --> |
6 |
|
7<html xmlns = "http://www.w3.org/1999/xhtml">
8<head>
9<title>Handling an HTTP Get Request</title>
10</head>
11
12<body>
13<form action = "/jhtp6/welcome1" method = "get" >
14<p><label>Click the button to invoke the servlet
15<input type = "submit" value = "Get HTML Document" />
16</label></p>
17</form>
18</body>
19</html>
[View full size image]
Microsoft's IIS.
Ports in this case are not physical hardware ports to which you attach cablesthey are logical locations named with integer values that allow clients to request different services on the same server. The port number specifies the logical location where a server waits for and receives connections from clientsthis is also called the handshake point. A client connecting to a server to request a service must specify the port number for that service; otherwise, the request cannot be processed. Port numbers are positive integers with values up to 65,535, and there are separate sets of these numbers for both the TCP and UDP protocols. Many operating systems reserve port numbers below 1024 for system services (such as e-mail and World Wide Web servers). Generally, these ports should not be specified as connection ports in your own server programs. In fact, some operating systems require special access privileges to use port numbers below 1024.
[Page 1250]
With so many ports from which to choose, how does a client know which port to use when requesting a service? The term well-known port number is often used when describing popular services on the Internet, such as Web servers and e-mail servers. All Web browsers know 80 as the well-known port on a Web server where requests for HTML documents are made. So when you type a URL into a Web browser, the browser by default connects to port 80 on the server. Because, the Tomcat server uses port 8080 as its port number, requests to Tomcat for Web pages or to invoke servlets and JavaServer Pages must specify that the Tomcat server listens on port 8080.
[Page 1251]
The client can access the servlet only if it is installed on a server that can respond to servlet requests. In some cases, servlet support is built directly into the Web server, and no special configuration is required to handle servlet requests. In other cases, it is necessary to integrate a servlet container with a Web server (as can be done with Tomcat and the Apache or IIS Web servers). Web servers that support servlets normally have an installation procedure for servlets. If you intend to execute your servlet as part of a Web server, please refer to your server's documentation on how to install a servlet. For our examples, we demonstrate servlets with the Apache Tomcat server. Section 26.3 discusses the setup and configuration of Tomcat for use with this chapter. Section 26.4.1 discusses the deployment of the servlet in Fig. 26.7.
26.4.1. Deploying a Web Application
JSPs, servlets and their supporting files are deployed as part of Web applications. Normally, Web applications are deployed in the webapps subdirectory of jakarta-tomcat-5.0.25. A Web application has a well-known directory structure in which all the files that are part of the application reside. This structure can be created by the server administrator in the webapps directory, or the entire directory structure can be archived in a Web application archive file. Such an archive is known as a WAR file and ends with the .war file extension. Such files are typically placed in the webapps directory. When the Tomcat server begins execution, it extracts the WAR file's contents into the appropriate webapps subdirectory structure. For simplicity as we teach servlets and JavaServer Pages, we create the already expanded directory structure for all the examples in this chapter.
The Web application directory structure contains a context rootthe top-level directory for an entire Web applicationand several subdirectories. These are described in Fig. 26.9.
Figure 26.9. Web application standard directories.
(This item is displayed on page 1252 in the print version)
Directory |
Description |
|
|
context root |
This is the root directory for the Web application. All the JSPs, |
|
HTML documents, servlets and supporting files such as images |
|
and class files reside in this directory or its subdirectories. The |
|
name of this directory is specified by the Web application |
|
creator. To provide structure in a Web application, subdirectories |
|
can be placed in the context root. For example, if your |
|
application uses many images, you might place an images |
|
subdirectory in this directory. The examples of this chapter use |
|
jhtp6 as the context root. |
WEB-INF |
This directory contains the Web application deployment |
|
descriptor (web.xml). |
WEB-INF/classes |
This directory contains the servlet class files and other |
|
supporting class files used in a Web application. If the classes |
|
are part of a package, the complete package directory structure |
|
would begin here. |
WEB-INF/lib |
This directory contains Java archive (JAR) files. The JAR files can |
|
contain servlet class files and other supporting class files used in |
|
a Web application. |
|
|
Common Programming Error 26.1
Using "servlet" or "servlets" as a context root may prevent a servlet from working correctly on some servers. x
Configuring the context root for a Web application in Tomcat requires creating a subdirectory in the webapps directory. When Tomcat begins execution, it creates a context root for each subdirectory of webapps, using each subdirectory's name as a context root name. To test the examples in this chapter, create the directory jhtp6 in Tomcat's webapps directory.
After configuring the context root, we must configure our Web application to handle the requests. This configuration occurs in a deployment descriptor, which is stored in a file called web.xml. This specifies various configuration parameters, such as the name used to invoke the servlet (i.e., its alias), a description of the servlet, the servlet's fully qualified class name and a servlet mapping (i.e., the path or paths that cause the servlet container to invoke the servlet). You must create the web.xml file for this example. Many Java Web application deployment tools create the web.xml file for you. The one for the first example in this chapter is shown in Fig. 26.10. We will enhance this file as we add other servlets to the Web application throughout this chapter.
Figure 26.10. Deployment descriptor (web.xml) for the jhtp6 Web application.
(This item is displayed on page 1253 in the print version)
1<web-app xmlns= "http://java.sun.com/xml/ns/j2ee"
2xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
4http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
5version="2.4">
6
7 <!-- General description of your Web application -->
8<display-name>
9Java How to Program JSP
10and Servlet Chapter Examples
11</display-name>
12
13<description>
14This is the Web application in which we
15demonstrate our JSP and Servlet examples.
16</description>
17
18<!-- Servlet definitions -->
19<servlet>
20<servlet-name>welcome1</servlet-name>
22<description>
23A simple servlet that handles an HTTP get request.
24</description>
25
26<servlet-class>
27WelcomeServlet
28</servlet-class>
29</servlet>
30
31<!-- Servlet mappings -->
32<servlet-mapping>
33<servlet-name>welcome1</servlet-name>
34<url-pattern>/welcome1</url-pattern>
35</servlet-mapping>
36
37 </web-app>
[Page 1252]
Element web-app (lines 137) defines the configuration of each servlet in the Web application and the servlet mapping for each servlet. Element display-name (lines 811) specifies a name that can be displayed to the administrator of the server on which the Web application is installed. Element description (lines 1316) specifies a description of the Web application that might be displayed to the server administrator.
Element servlet (lines 1929) describes a servlet. Element servlet-name (line 20) is the name we chose for the servlet (welcome1). Element description (lines 2224) specifies a description for this particular servlet. Again, this can be displayed to the server administrator. Element servlet-class (lines 2628) specifies the compiled servlet's fully qualified class name. Thus, the servlet welcome1 is defined by class WelcomeServlet.
Element servlet-mapping (lines 3235) specifies servlet-name and url-pattern elements. The URL pattern helps the server determine which requests are sent to the servlet (welcome1). Our Web application will be installed as part of the jhtp6 context root discussed in Section 26.4.1. Thus, the relative URL we supply to the browser to invoke the servlet in this example is
/jhtp6/welcome1
where /jhtp6 specifies the context root that helps the server determine which Web application handles the request and /welcome1 specifies the URL pattern that is mapped to servlet welcome1 to handle the request. Note that the server on which the servlet resides is not specified here, although this can be done as follows:
http://localhost:8080/jhtp6/welcome1
[Page 1253]
If the explicit server and port number are not specified as part of the URL, the browser assumes that the form handler (i.e., the value of the action attribute of the form element in HTML) resides at the same server and port number from which the browser downloaded the Web page containing the form.
There are several URL pattern formats that can be used. The /welcome1 URL pattern requires an exact match of the pattern. You can also specify path mappings, extension mappings and a default servlet for a Web application. A path mapping begins with a / and ends with a /*. For example, the URL pattern
/jhtp6/example/*
Actually, the HTML file in Fig. 26.8 was not necessary to invoke this servlet. A get request can be sent to a server simply by typing the URL in a browserexactly as you do when you request a Web page in the browser. In this example, you can type
http://localhost:8080/jhtp6/welcome1
in the Address or Location field of your browser to invoke the servlet directly.
Error-Prevention Tip 26.3
You can test a servlet that handles HTTP get requests by typing the
URL that invokes the servlet directly into your browser's Address or
Location field because get is the default HTTP method when browsing.
[Page 1255 (continued)]
26.5. Handling HTTP get Requests Containing Data
When requesting a document or resource from a Web server, it is possible to supply data as part of the request. The servlet WelcomeServlet2 in Fig. 26.12 responds to an HTTP get request that contains a name supplied by the user. The servlet uses the name as part of the response to the client.
Figure 26.12. WelcomeServlet2 responds to a get request containing data.
(This item is displayed on page 1256 in the print version)
1 // Fig. 26.12: WelcomeServlet2.java
2 // Processing HTTP get requests containing data.
3import javax.servlet.ServletException;
4import javax.servlet.http.HttpServlet;
5import javax.servlet.http.HttpServletRequest;
6import javax.servlet.http.HttpServletResponse;
7import java.io.IOException;
8import java.io.PrintWriter;
9
10public class WelcomeServlet2 extends HttpServlet
11{
12// process "get" request from client
13protected void doGet( HttpServletRequest request,
14HttpServletResponse response )
15throws ServletException, IOException
16{
17String firstName = request.getParameter( "firstname" );
19response.setContentType( "text/html" );
20PrintWriter out = response.getWriter();
22// send XHTML document to client
24// start XHTML document
25out.println( "<?xml version = \"1.0\"?>" );
27out.printf( "%s%s%s" , "<!DOCTYPE html PUBLIC" ,
28" \"-//W3C//DTD XHTML 1.0 Strict//EN\"",
29" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" );
31out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
33// head section of document
34out.println( "<head>" );
35out.println(
36"<title>Processing get requests with data</title>" );
37out.println( "</head>" );
38
39// body section of document
40out.println( "<body>" );
41out.println( "<h1>Hello " + firstName + ",<br />" );
42out.println( "Welcome to Servlets!</h1>" );
43out.println( "</body>" );
44
45// end XHTML document
46out.println( "</html>" );
47 out.close(); // close stream to complete the page
48} // end method doGet
49} // end class WelcomeServlet2
Parameters are passed as name-value pairs in a get request. Line 17 demonstrates how to obtain information that was passed to the servlet as part of the client request. The request object's getParameter method accepts the parameter name as an argument and returns the corresponding String value, or null if the parameter is not part of the request. Note that parameter names are case sensitive and must match exactly. Line 41 uses the result of line 17 as part of the response to the client.
The WelcomeServlet2.html document (Fig. 26.13) provides a form in which the user can input a name in the text input element firstname (line 16) and click the Submit button to invoke WelcomeServlet2. When the user presses the Submit button, the values of the input elements are placed in name-value pairs as part of the request to the server. In the second screen capture in Fig. 26.13, note that the browser appended
?firstname=Jon
to the end of the action URL. The ? separates the query string (i.e., the data passed as part of the get request) from the rest of the URL in a get request. The name-value pairs are passed with the name and the value separated by =. If there is more than one namevalue pair, each pair is separated by &.
Figure 26.13. HTML document in which the form's action invokes
WelcomeServlet2 through the alias welcome2 specified in web.xml.
(This item is displayed on page 1257 in the print version)
1 |
<?xml version = "1.0"?> |
2 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" |
3 |
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> |
4 |
|
5 |
<!-- Fig. 26.13: WelcomeServlet2.html --> |
6 |
|
7<html xmlns = "http://www.w3.org/1999/xhtml">
8<head>
9<title>Processing get requests with data </title>
10</head>
11
12<body>
13<form action = "/jhtp6/welcome2" method = "get" >
14<p><label>
15Type your first name and press the Submit button
16<br /><input type = "text" name = "firstname" />
17<input type = "submit" value = "Submit" />
18</p></label>
19</form>
20</body>
21</html>
[View full size image]
