Servlet Overview and Architecture
This section overviews Java servlet technology, discussing at a high level the servlet-related classes, methods and exceptions. The next several sections present examples in which we build multitier client-server systems using servlet and JDBC technology.
The Internet offers many protocols. The HTTP (Hypertext Transfer Protocol) that forms the basis of the World Wide Web uses URLs (Uniform Resource Locators) to locate resources on the Internet. Common URLs represent files or directories and can represent complex tasks such as database lookups and Internet searches. For more information on URL formats, visit www.w3.org/Addressing. For more information on the HTTP protocol, visit www.w3.org/Protocols/HTTP. For information on a variety of World Wide Web topics, visit the World Wide Web Consortium's Web sitewww.w3.org.
JavaServer Pages technology, an extension of servlet technology, simplifies the process of creating pages by separating presentation from content. Normally, JSPs are used when most of the content sent to the client is static text and markup, and only a small portion of the content is generated dynamically with Java code. Servlets commonly are used when a small portion of the content sent to the client is static text or markup. In fact, some servlets do not produce content. Rather, they perform a task on behalf of the client, then invoke other servlets or JSPs to provide a response. Note that in most cases servlet and JSP technologies are interchangeable. The server that executes a servlet is referred to as the servlet container or servlet engine.
Servlets and JavaServer Pages have become so popular that they are now supported directly or with third-party plug-ins by most major Web servers and application serversservers that execute applications to generate dynamic Web pages in response to requests. Several popular Web servers and application servers include the Sun Java System Application Server (wwws.sun.com/software/products/appsrvr/home_appsrvr.html), Microsoft's Internet Information Services (IIS) (www.microsoft.com/iis), the Apache HTTP Server (httpd.apache.org/), BEA's WebLogic application server (www.bea.com/products/weblogic/server/index.shtml), IBM's WebSphere application server (www-3.ibm.com/software/webservers/appserv/) and the World Wide Web Consortium's Jigsaw Web server (www.w3.org/Jigsaw/).
The servlets in this chapter demonstrate communication between clients and servers via the HTTP protocol (Fig. 26.1). A client sends an HTTP request to the server. The servlet container receives the request and directs it to be processed by the appropriate servlet. The servlet does its processing, which may include interacting with a database or other server-side components, such as other servlets or JSPs. The servlet returns its results to the clientnormally in the form of an HTML, XHTML or XML (Extensible Markup Language, which is used to exchange structured data on the Web) document to display in a browser. Other data formats, such as images and binary data, can also be returned.
Figure 26.1. Servlet architecture.
26.2.1. Interface Servlet and the Servlet Life Cycle
Architecturally, all servlets must implement the Servlet interface of package javax.servlet. The methods of interface Servlet are invoked by the servlet container. This interface declares five methods described in Fig. 26.2. You can view the details of the Servlet interface online at java.sun.com/j2ee/1.4/docs/api/javax/servlet/Servlet.html.
Method |
Description |
---|---|
void init( ServletConfig config ) |
|
The servlet container calls this method once during a servlet's execution cycle to initialize the servlet. The ServletConfig argument is supplied by the servlet container that executes the servlet. |
|
ServletConfig getServletConfig() |
|
This method returns a reference to an object that implements interface ServletConfig. This object provides access to the servlet's configuration information, such as its initialization parameters and ServletContext, which provides the servlet with access to its environment (i.e., the servlet container in which the servlet executes). |
|
String getServletInfo() |
|
This method is defined by a servlet programmer to return a string containing servlet information, such as the servlet's author and version. |
|
void service( ServletRequest request, ServletResponse response ) |
|
The servlet container calls this method to respond to a client request to the servlet. |
|
void destroy() |
|
This "cleanup" method is called when a servlet is terminated by its servlet container. Resources used by the servlet, such as open files or open database connections, should be deallocated here. |
Software Engineering Observation 26.1
Servlets implement the Servlet interface of package javax.servlet |
A servlet's life cycle begins when the servlet container loads it into memorynormally, in response to the first request for the servlet. Before the servlet can handle that request, the container invokes the servlet's init method. After init completes execution, the servlet can respond to its first request. All requests are handled by a servlet's service method, which receives the request, processes it and sends a response to the client. During a servlet's life cycle, method service is called once per request. Each new request is typically handled in a separate thread of execution (managed by the servlet container) in which method service executes. When the servlet container terminates the servlet (e.g., when the servlet container needs more memory or when it is shut down), the servlet's destroy method is called to release servlet resources.
The servlet packages define two abstract classes that implement interface Servletclass GenericServlet (from the package javax.servlet) and class HttpServlet (from the package javax.servlet.http). These classes provide default implementations of some Servlet methods. Most servlets extend either GenericServlet or HttpServlet and override some or all of their methods. The GenericServlet is a protocol-independent servlet, while the HTTPServlet uses the HTTP protocol to exchange the information between the server and the client. HTTPServlet is used on the Web. If your servlets need to implement protocols other than HTTP, they may extend GenericServlet. To extend GenericServlet, the servlet must override the abstract method service. To extend HttpServlet, the servlet must override at least one method declared in class HttpServlet.
The examples in this chapter all extend class HttpServlet, which defines enhanced processing capabilities for servlets that extend a Web server's functionality. The key method in every servlet is service, which accepts both a ServletRequest object and a ServletResponse object. These objects provide access to input and output streams that allow the servlet to read data from and send data to the client. These streams can be either byte based or character based. If problems occur during the execution of a servlet, either ServletExceptions or IOExceptions are thrown to indicate the problem.
26.2.2. HttpServlet Class
Servlets typically extend class HttpServlet, which overrides method service to distinguish between the typical requests received from a client Web browser. The two most common HTTP request types (also known as request methods) are get and post. A get request gets (or retrieves) information from a server. Such requests often retrieve an HTML document or an image. A post request posts (or sends) data to a server, such as authentication information or data from a form that gathers user input. Usually, post requests are used to post a message to a news group or a discussion forum, pass user input to a data-handling process and store or update the data on a server.
Class HttpServlet defines methods doGet and doPost to respond to get and post requests from a client, respectively. These methods are called by method service, which is called by the servlet container when a request arrives at the server. Method service first determines the request type, then calls the appropriate method for handling such a request. Methods of class HttpServlet that respond to the other request types are shown in Fig. 26.3. For more details about these methods, visit java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServlet.html. Each method accepts parameters of type HttpServletRequest and HttpServletResponse and returns void. These methods are not frequently used.
Method |
Description |
---|---|
doDelete |
Called in response to an HTTP delete request. Such a request is normally used to delete a file from a server. This may not be available on some servers because of its inherent security risks (e.g., the client could delete a file that is critical to the execution of the server or an application). |
doHead |
Called in response to an HTTP head request. Such a request is normally used when the client wants only the response's headers, such as its content type and content length. By overriding this method, the servlet does not compute the response body, thus improving performance. |
doOptions |
Called in response to an HTTP options request. This returns information to the client indicating the HTTP options supported by the server, such as the HTTP version (1.0 or 1.1) and the request methods the server supports. |
doPut |
Called in response to an HTTP put request. Such a request is normally used to store a file on the server. This may not be available on some servers because of its inherent security risks (e.g., the client could place an executable application on the server, which, if executed, could damage the serverperhaps by deleting critical files or occupying resources). |
doTrace |
Called in response to an HTTP trace request. Such a request is normally used for debugging. The implementation of this method automatically returns an HTML document to the client containing the requestheader information (data sent by the browser as part of the request). |
Software Engineering Observation 26.2
Do not override method service in an HttpServlet subclass. Doing so prevents the servlet from distinguishing between request types. |
Methods doGet and doPost accept as arguments an HttpServletRequest object and an HttpServletResponse object that enable interaction between the client and the server. The methods of HttpServletRequest allow access to the data supplied as part of the request. The HttpServletResponse methods make it easy to return the servlet's results to the Web client. Interfaces HttpServletRequest and HttpServletResponse are discussed in the next two sections.
26.2.3. HttpServletRequest Interface
Every call to doGet or doPost for an HttpServlet receives an object that implements interface HttpServletRequest. The servlet container creates an HttpServletRequest object and passes it to the servlet's service method (which, in turn, passes it to doGet or doPost). This object contains the client's request and provides methods that enable the servlet to process the request. Some methods are from interface ServletRequestthe interface that HttpServletRequest extends. A few key methods used in this chapter are presented in Fig. 26.4. You can view a complete list of HttpServletRequest methods online at java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletRequest.html. You can also install Tomcat (discussed in Section 26.3) and view the documentation on your local computer.
Method |
Description |
---|---|
String getParameter( String name ) |
|
Obtains the value of a parameter sent to the servlet as part of a get or post request. The name argument represents the parameter name. |
|
Enumeration getParameterNames() |
|
Returns the names of all the parameters sent to the servlet as part of a post request. |
|
String[] getParameterValues( String name ) |
|
For a parameter with multiple values, this method returns an array of strings containing the values for a specified servlet parameter. |
|
Cookie[] getCookies() |
|
Returns an array of Cookie objects stored on the client by the server. Cookie objects can be used to uniquely identify clients to the servlet. |
|
HttpSession getSession( boolean create ) |
|
Returns an HttpSession object associated with the client's current browsing session. This method can create an HttpSession object (TRue argument) if one does not already exist for the client. HttpSession objects and Cookies are used in similar ways for uniquely identifying clients. |
|
String getLocalName() |
|
Gets the host name on which the request was received. |
|
String getLocalAddr() |
|
Gets the Internet Protocol (IP) address on which the request was received. |
|
int getLocalPort() |
|
Gets the Internet Protocol (IP) port number on which the request was received. |
26.2.4. HttpServletResponse Interface
Every call to doGet or doPost for an HttpServlet receives an object that implements interface HttpServletResponse. The servlet container creates an HttpServletResponse object and passes it to the servlet's service method (which, in turn, passes it to doGet or doPost). This object provides methods that enable the servlet to formulate the response to the client. Some of these are from interface ServletResponsethe interface that HttpServletResponse extends. A few key methods used in this chapter are presented in Fig. 26.5. You can view a complete list of HttpServletResponse methods online at java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletResponse.html. You can also view the documentation on your local computer through Tomcat.
Method |
Description |
---|---|
void addCookie( Cookie cookie ) |
|
Used to add a Cookie to the header of the response to the client. The Cookie's maximum age and whether Cookies are enabled on the client determine whether Cookies are stored on the client. |
|
ServletOutputStream getOutputStream() |
|
Obtains a byte-based output stream for sending binary data to the client. |
|
PrintWriter getWriter() |
|
Obtains a character-based output stream for sending text data (usually HTML formatted text) to the client. |
|
void setContentType( String type ) |
|
Specifies the content type of the response to the browser. The content type helps the browser determine how to display the data (or possibly what other application to execute to process the data). The content type is also known as MIME (Multipurpose Internet Mail Extension) type of the data. For examples, content type "text/html" indicates that the response is an HTML document, so the browser displays the HTML page; content type "image/gif" indicates that the response is an image, so the browser displays the image. For a complete list of content types, visit www.isi.edu/in-notes/iana/assignments/mediatypes/media-types. |
|
String getContentType() |
|
Gets the content type of the response. |