.NODE

Handling HTTP get Requests

The primary purpose of an HTTP get request is to retrieve the content of a specified URLnormally an HTML or XHTML document. The servlet in Fig. 26.7 and the XHTML document in Fig. 26.8 demonstrate a servlet that handles HTTP get requests. When the user clicks the Get HTML Document button (Fig. 26.8), a get request is sent to the servlet WelcomeServlet (Fig. 26.7). The servlet responds to the request by dynamically generating an XHTML document for the client that displays "Welcome to Servlets!". Figure 26.7 shows the WelcomeServlet source code. Figure 26.8 shows the XHTML document the client loads to access the servlet and shows screen captures of the client's browser window before and after the servlet interaction. [ Note: Section 26.3 discusses how to set up and configure Tomcat to execute this example.]

Figure 26.7. WelcomeServlet that responds to a simple HTTP get request.

(This item is displayed on page 1248 in the print version)

""A Simple Servlet Example

 1 // Fig. 26.7: WelcomeServlet.java
 2 // A simple servlet to process get requests.
 3 import javax.servlet.ServletException; 
 4 import javax.servlet.http.HttpServlet; 
 5 import javax.servlet.http.HttpServletRequest; 
 6 import javax.servlet.http.HttpServletResponse;
 7 import java.io.IOException;
 8 import java.io.PrintWriter;
 9
10 public class WelcomeServlet extends HttpServlet
11 {
12 // process "get" requests from clients 
13 protected void doGet( HttpServletRequest request,
14  HttpServletResponse response ) 
15  throws ServletException, IOException 
16 {
17 response.setContentType( "text/html" );
18 PrintWriter out = response.getWriter();
19
20 // send XHTML page to client
21
22 // start XHTML document 
23 out.println( "" );
24
25 out.printf( "%s%s%s" , ",
26 " "-//W3C//DTD XHTML 1.0 Strict//EN"",
27 " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
" );
28
29 out.println( "
); 30 31 // head section of document 32 out.println( " ); 33 out.println( " " ); 34 out.println( "" ); 35 36 // body section of document 37 out.println( " ); 38 out.println( "

Welcome to Servlets!

" ); 39 out.println( "" ); 40 41 // end XHTML document 42 out.println( "" ); 43 out.close(); // close stream to complete the page 44 } // end method doGet 45 } // end class WelcomeServlet

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)

"http://www.w3.org/1999/xhtml"> 8 9

 1  "1.0"?>
 2  "-//W3C//DTD XHTML 1.0 Strict//EN"
 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4
 5 
 6
 7 
Handling an HTTP Get Request 10 11 12 13 "/jhtp6/welcome1" method = "get" > 14

Click the button to invoke the servlet 15 "submit" value = "Get HTML Document" /> 16

17 18 19

Lines 36 import various classes in the javax.servlet and javax.servlet.http packages. We use several data types from these packages in the example. Package javax.servlet.http provides superclass HttpServlet for servlets that handle HTTP get requests and HTTP post requests. This class implements interface javax.servlet.Servlet and adds methods that support HTTP protocol requests. Class WelcomeServlet extends HttpServlet (line 10) for this reason.

Superclass HttpServlet provides method doGet to respond to get requests. Its default functionality is to indicate a "Method not supported" error. Typically, this error is indicated in Internet Explorer and in Netscape with a Web page that states "HTTP status 405." Lines 1344 override method doGet to provide custom get request processing. Method doGet accepts two argumentsan HttpServletRequest object and an HttpServletResponse object (both from package javax.servlet.http). The HttpServletRequest object represents the client's request, and the HttpServletResponse object represents the server's response to the client. If method doGet is unable to handle a client's request, it throws an exception of type javax.servlet.ServletException. If doGet encounters an error during stream processing (reading from the client or writing to the client), it throws a java.io.IOException.

To demonstrate a response to a get request, our servlet creates an XHTML document containing the text "Welcome to Servlets!" The text of the XHTML document is the response to the client. The response is sent to the client through the PrintWriter object obtained from the HttpServletResponse object.

Line 17 uses the response object's setContentType method to specify the content type of the data to be sent as the response to the client. This enables the client browser to understand and handle the content. The content type is also known as the MIME (Multipurpose Internet Mail Extension) type of the data. In this example, the content type is text/html to indicate to the browser that the response is an XHTML document. The browser knows that it must read the XHTML tags, format the document accordingly and display it in the browser window.

Line 18 uses the response object's getWriter method to obtain a reference to the PrintWriter object that enables the servlet to send content to the client. [Note: If the response is binary data, such as an image, method getOutputStream is used to obtain a reference to a ServletOutputStream object.]

Lines 2342 create the XHTML document by writing strings with the out object's println method. This method outputs a newline character after its String argument. When rendering the Web page, the browser does not use the newline character. Rather, the newline character appears in the XHTML source that you can see by selecting Source from the View menu in Internet Explorer or Page Source from the View menu in Netscape. Line 43 closes the output stream, flushes the output buffer and sends the information to the client.

The XHTML document in Fig. 26.8 provides a form that invokes the servlet defined in Fig. 26.7. The form's action attribute (/jhtp6/welcome1) specifies the URL path that invokes the servlet, and the form's method attribute indicates that the browser sends a get request to the server, which results in a call to the servlet's doGet method. The URL specified as the action in this example is discussed in detail in Section 26.4.1 after we show how to set up and configure the Apache Tomcat server to execute the servlet in Fig. 26.7.

Note that the sample screen captures show a URL containing the server name localhosta well-known server host name on most computers that support TCP/IP-based networking protocols such as HTTP. We often use localhost to demonstrate networking programs on the local computer, so that readers without a network connection can still learn network programming concepts. In this example, localhost indicates that the server on which the servlet is installed is running on the local machine. The server host name is followed by :8080, specifying the TCP port number at which the Tomcat server listens for requests from clients. Web browsers assume TCP port 80 by default as the server port at which clients make requests, but the Tomcat server listens for client requests at TCP port 8080. This allows Tomcat to execute on the same computer as a standard Web server application without affecting the Web server's ability to handle requests. If we do not explicitly specify the port number in the URL, the servlet will not receive our request and an error message will be displayed in the browser.

Software Engineering Observation 26.3

The Tomcat documentation specifies how to integrate Tomcat with popular Web server applications such as the Apache HTTP Server and 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.

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.

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  xmlns= "http://java.sun.com/xml/ns/j2ee" 
 2  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
 4  http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" 
 5  version="2.4"> 
 6
 7 
 8  
 9  Java How to Program JSP 
10  and Servlet Chapter Examples 
11  
12
13  
14  This is the Web application in which we 
15  demonstrate our JSP and Servlet examples.
16  
17
18  
19  
20  welcome1 
21 
22   
23  A simple servlet that handles an HTTP get request.
24   
25 
26   
27  WelcomeServlet 
28   
29  
30
31  
32  
33  welcome1
34  /welcome1 
35  
36
37 

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

 

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/*

 

indicates that any URL path beginning with /jhtp6/example/ will be sent to the servlet that has the preceding URL pattern. An extension mapping begins with *. and ends with a file-name extension. For example, the URL pattern

 *.jsp

 

indicates that any request for a file with extension .jsp will be sent to the servlet that handles JSP requests. In fact, servers with JSP containers have an implicit mapping of the .jsp extension to a servlet that handles JSP requests. The URL pattern / represents the default servlet for the Web application. This is similar to the default document of a Web server. For example, if you type the URL www.deitel.com into your Web browser, the document you receive from our Web server is the default document index.html. If the URL pattern matches the default servlet for a Web application, that servlet is invoked to return a default response to the client. This can be useful for personalizing Web content to specific users. To compile your servlet, you will need to use javac's -classpath option to specify the name and location of the file servlet-api.jar, which is located in Tomcat's commonlibs directory. Finally, we are ready to place our files into the appropriate directories to complete the deployment of our first servlet for testing. We have three files to placeWelcomeServlet.html, WelcomeServlet.class and web.xml. In your jakarta-tomcat-5.0.25webappsjhtp6 directorythe context root for our Web applicationcreate subdirectories named servlets and WEB-INF. We place our HTML files for this servlets chapter in the servlets directory. Copy the WelcomeServlet.html file into the servlets directory. In the WEB-INF directory, create the subdirectory classes, then copy the web.xml file into the WEB-INF directory, and copy the WelcomeServlet.class file into the classes directory. Thus, the directory and file structure under the webapps directory should be as shown in Fig. 26.11 (file names are in italics).After the files are placed in the proper directories, start the Tomcat server, open your browser and type the following URL

 http://localhost:8080/jhtp6/servlets/WelcomeServlet.html

 

Figure 26.11. Web application directory and file structure for WelcomeServlet.

WelcomeServlet Web application directory and file structure

jhtp6
 servlets
 WelcomeServlet.html
 WEB-INF
 web.xml
 classes
 WelcomeServlet.class
 

 

to load WelcomeServlet.html into the Web browser. Then click the Get HTML Document button to invoke the servlet. You should see the results shown in Fig. 26.8. You can try this servlet from several different Web browsers to demonstrate that the results are the same across Web browsers.

Common Programming Error 26.2

Not placing a servlet or other class files in the appropriate directory structure prevents the server from locating those classes properly. This results in an error response to the client Web browser.

 

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.


Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover





Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615
Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net