Você está na página 1de 27

Java Servlet Technology

As soon as the Web began to be used for delivering services, service providers recognized the need for dynamic
content. Applets, one of the earliest attempts toward this goal, focused on using the client platform to deliver
dynamic user experiences. At the same time, developers also investigated using the server platform for this
purpose. Initially, Common Gateway Interface (CGI) scripts were the main technology used to generate dynamic
content. Although widely used, CGI scripting technology has a number of shortcomings, including platform
dependence and lack of scalability. To address these limitations, Java Servlet technology was created as a portable
way to provide dynamic, user-oriented content.

What is a Servlet?
A servlet is a JavaTM technology-based Web component, managed by a container that generates dynamic content.
Like other Java technology-based components, servlets are platform-independent Java classes that are compiled to
platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.
Containers, sometimes called servlet engines, are Web server extensions that provide servlet functionality. Servlets
interact with Web clients via a request/response paradigm implemented by the servlet container.
The Java Servlet API allows a software developer to add dynamic content to a Web server using the Java platform.
The generated content is commonly HTML, but may be other data such as XML. Servlets can maintain state across
many server transactions by using HTTP cookies, session variables or URL rewriting.
Servlets are pieces of Java source code that add functionality to a web server in a manner similar to the way applets
add functionality to a browser. Servlets are designed to support a request/response computing model that is
commonly used in web servers. In a request/response model, a client sends a request message to a server and the
server responds by sending back a reply message.
A servlet is a generic server extension—a Java class that can be loaded dynamically to expand the functionality of a
server. Servlets are commonly used with web servers, where they can take the place of CGI scripts. A servlet is
similar to a proprietary server extension, except that it runs inside a Java Virtual Machine (JVM) on the server (see
Figure-1), so it is safe and portable. Servlets operate solely within the domain of the server: unlike applets, they do
not require support for Java in the web browser.
Unlike CGI and FastCGI, which use multiple processes to handle separate programs and/or separate requests,
servlets are all handled by separate threads within the web server process. This means that servlets are also
efficient and scalable. Because servlets run within the web server, they can interact very closely with the server to
do things that are not possible with CGI scripts.

Servlet Container
The servlet container is a part of a Web server or application server that provides the network services over which
requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet
container also contains and manages servlets through their lifecycle.
A servlet container can be built into a host Web server, or installed as an add-on component to a Web Server via
that server’s native extension API. Servlet containers can also be built into or possibly installed into Web-enabled
application servers.
All servlet containers must support HTTP as a protocol for requests and responses, but additional
request/response-based protocols such as HTTPS (HTTP over SSL) may be supported. A servlet container may place
security restrictions on the environment in which a servlet executes.

Page 1
Java Servlet Technology
Java Servlet-based Web Server

Main Process
JVM
Request for Servlet 1 Thread
Servlet 1

Request for Servlet 2 Thread

Request for Servlet 1 Thread Servlet 2

Figure 1: Servlet in JVM

The servlet container is a compiled, executable program. The container is the intermediary between the Web
server and the servlets in the container. The container loads, initializes, and executes the servlets. When a request
arrives, the container maps the request to a servlet, translates the request into C++ objects, and then passes the
request to the servlet. The servlet processes the request and produces a response. The container translates the
response into the network format, and then sends the response back to the Web server.
The container is designed to perform well while serving large numbers of requests. A container can hold any
number of active servlets, filters, and listeners. Both the container and the objects in the container are
multithreaded. The container creates and manages threads as necessary to handle incoming requests. The
container handles multiple requests concurrently, and more than one thread may enter an object at a time.
Therefore, each object within a container must be thread-safe.

Java Servlet API


The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets.
All servlets must implement the Servlet interface, which defines life-cycle methods. When implementing a
generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The
HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.

Servlet Interface
Architecturally, all servlets must implement the Servlet interface. As with many key applet methods, the
methods of interface Servlet are invoked automatically (by the server on which the servlet is installed, also
known as the servlet container).
To implement this interface, you can write a generic servlet that extends javax.servlet.GenericServlet
or an HTTP servlet that extends javax.servlet.http.HttpServlet. This interface defines methods to
initialize a servlet, to service requests, and to remove a servlet from the server. This interface defines five methods
described below:

Method Description

void init( ServletConfig config ) throws ServletException

This method is automatically called 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()

Page 2
Java Servlet Technology
This method returns a reference to an object that implements interface ServletConfig. This
object provides access to the servlet’s configuration information such as servlet initialization
parameters and the servlet’s 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 ) throws


ServletException, IOException

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 an open file or an open database connection, should be de-allocated here.

The servlet packages define two abstract classes that implement the interface Servlet—class
GenericServlet (from the package javax.servlet) and class HttpServlet (from the package
javax.servlet.http). These classes provide default implementations of all the Servlet methods. Most
servlets extend either GenericServlet or HttpServlet and override some or all of their methods.
The key method in every servlet is service, which receives 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 the client 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.

Number of Instances
The servlet declaration which is part of the deployment descriptor of the Web application containing the servlet
controls how the servlet container provides instances of the servlet.
For a servlet not hosted in a distributed environment (the default) the servlet container must use only one instance
per servlet declaration. However, for a servlet implementing the SingleThreadModel interface, the servlet
container may instantiate multiple instances to handle a heavy request load and serialize requests to a particular
instance.
The use of the SingleThreadModel interface guarantees that only one thread at a time will execute in a given
servlet instance’s service method. It is important to note that this guarantee only applies to each servlet instance,
since the container may choose to pool such objects. Objects that are accessible to more than one servlet instance
at a time, such as instances of HttpSession, may be available at any particular time to multiple servlets,
including those that implement SingleThreadModel.

ServletContext Interface
The ServletContext interface defines a servlet’s view of the Web application within which the servlet is
running. The Container Provider is responsible for providing an implementation of the ServletContext
interface in the servlet container. Using the ServletContext object, a servlet can log events, obtain URL
references to resources, and set and store attributes that other servlets in the context can access.
There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets
and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed
via a .war file.). The ServletContext object is contained within the ServletConfig object, which the Web server
provides the servlet when the servlet is initialized.

Page 3
Java Servlet Technology
A ServletContext is rooted at a known path within a Web server. For example, a servlet context could be
located at http://www.mycorp.com/catalog. All requests that begin with the /catalog request path, known as the
context path, are routed to the Web application associated with the ServletContext.
There is one instance object of the ServletContext interface associated with each Web application deployed
into a container. In cases where the container is distributed over many virtual machines, a Web application will
have an instance of the ServletContext for each JVM.

Method Description

String getInitParameter(String name)

Returns a String containing the value of the named context-wide initialization parameter, or null
if the parameter does not exist. This method can make available configuration information useful to
an entire "web application".

Enumeration getInitParameterNames()

Returns the names of the context's initialization parameters as an Enumeration of String


objects, or an empty Enumeration if the context has no initialization parameters.

Object getAttribute(String name)

Returns the servlet container attribute with the given name, or null if there is no attribute by that
name. An attribute allows a servlet container to give the servlet additional information not already
provided by this interface. See your server documentation for information about its attributes. A list
of supported attributes can be retrieved using getAttributeNames.

void setAttribute(String name, Object object)

Binds an object to a given attribute name in this servlet context. If the name specified is already used
for an attribute, this method will replace the attribute with the new to the new attribute. If a null
value is passed, the effect is the same as calling removeAttribute().

void removeAttribute(String name)

Removes the attribute with the given name from the servlet context. After removal, subsequent calls
to getAttribute(java.lang.String) to retrieve the attribute's value will return null.

Enumeration getAttributeNames()

Returns an Enumeration containing the attribute names available within this servlet context.

HttpServlet Class
Web-based servlets typically extend class HttpServlet. Class HttpServlet 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.
Common uses of get requests are to retrieve an HTML document or an image. A post request posts (or sends) data
to a server. Common uses of post requests typically send information, such as authentication information or data
from a form that obtains user input, to 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 the service method, which is called 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 below. They all
receive parameters of type HttpServletRequest and HttpServletResponse and return void.
Page 4
Java Servlet Technology
Method Description
protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
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 (i.e., the
client could delete a file that is critical to the execution of the server or an application).
protected void doOption(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
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 version of HTTP (1.0 or 1.1) and the request
methods the server supports.
protected void doPut(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
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 (i.e., the
client could place an executable application on the server, which, if executed, could damage the
server—perhaps by deleting critical files or occupying resources).
protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
Called in response to an HTTP trace request. Such a request is normally used for debugging. The
implementation of this method automatically returns a\n HTML document to the client containing
the request header information (data sent by the browser as part of the request).
protected void doHead(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
Receives an HTTP HEAD request from the protected service method and handles the request. The
client sends a HEAD request when it wants to see only the headers of a response, such as Content-
Type or Content-Length. The HTTP HEAD method counts the output bytes in the response to set the
Content-Length header accurately.

Methods doGet and doPost receive as arguments an HttpServletRequest object and an


HttpServletResponse object that enable interaction between the client and the server. The methods of
HttpServletRequest make it easy to access the data supplied as part of the request. The
HttpServletResponse methods make it easy to return the servlet’s results to the Web client.

HttpServletRequest interface
Every call to doGet or doPost for an HttpServlet receives an object that implements interface
HttpServletRequest. The Web server that executes the servlet creates an HttpServletRequest object
and passes this to the servlet’s service method (which, in turn, passes it to doGet or doPost). This object
contains the request from the client. A variety of methods are provided to enable the servlet to process the client’s
request. Some of these methods are from interface ServletRequest—the interface that
HttpServletRequest extends. A few key methods used in this chapter are presented below:

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.

Page 5
Java Servlet Technology
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. Cookies 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. An
HttpSession object can be created by this method (true argument) if an HttpSession object
does not already exist for the client. HttpSession objects can be used in similar ways to Cookies
for uniquely identifying clients.

HtpServletResponse Interface
Every call to doGet or doPost for an HttpServlet receives an object that implements interface
HttpServletResponse. The Web server that executes the servlet 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 a variety of methods that enable the servlet to formulate the response to the client. Some of these
methods are from interface ServletResponse—the interface that HttpServletResponse extends. A few
key methods used in this chapter are presented below:

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 if 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 to the client.

void setContentType( String type )

Specifies the MIME type of the response to the browser. The MIME type helps the browser
determine how to display the data (or possibly what other application to execute to process the
data). For example, MIME type "text/html" indicates that the response is an HTML document, so the
browser displays the HTML page.

Page 6
Java Servlet Technology
Servlet Life Cycle
The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is
mapped to a servlet, the container performs the following steps.

1. If an instance of the servlet does not exist, the Web container


a. Loads the servlet class.
b. Creates an instance of the servlet class.
c. Initializes the servlet instance by calling the init method.
2. Invokes the service method, passing a request and response object.
3. If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy
method.

Handling HTTP GET Request


The primary purpose of an HTTP get request is to retrieve the content of a specified URL—normally the content is
an HTML or XHTML document (i.e., a Web page). The following example shows how to handle get request. The
servlet responds to the request by generating dynamically an XHTML document for the client that displays
“Welcome to Servlets!”.
1 // WelcomeServlet.java
2 // A simple servlet to process get requests.
3
4
5 import javax.servlet.*;
6 import javax.servlet.http.*;
7 import java.io.*;
8
9 public class WelcomeServlet extends HttpServlet {
10
11 // process "get" requests from clients
12 protected void doGet( HttpServletRequest request,
13 HttpServletResponse response )
14 throws ServletException, IOException
15 {
16 response.setContentType( "text/html" );
17 PrintWriter out = response.getWriter();
18
19 // send XHTML page to client
20
21 // start XHTML document
22 out.println( "<?xml version = \"1.0\"?>" );
23
24 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
25 "XHTML 1.0 Strict//EN\""http://www.w3.org" +
26 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
27
28 out.println(
29 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
30
31 // head section of document
32 out.println( "<head>" );
33 out.println( "<title>A Simple Servlet Example</title>" );
34 out.println( "</head>" );
35
36 // body section of document
37 out.println( "<body>" );

Page 7
Java Servlet Technology
38 out.println( "<h1>Welcome to Servlets!</h1>" );
39 out.println( "</body>" );
40
41 // end XHTML document
42 out.println( "</html>" );
43 out.close(); // close stream to complete the page
44 }
45 }

Figure 2: WelcomeServlet that responds to a simple HTTP get request.

Package javax.servlet.http provides super-class 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 9) for this reason.
Superclass HttpServlet provides method doGet to respond to get requests. Lines 12–44 override method
doGet to provide custom get request processing. Method doGet receives two arguments—an
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.
Line 16 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 also is known as the MIME type (Multipurpose Internet Mail Extension) 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 in the document, format the document according to the tags and display
the document in the browser window.
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 obtains
the reference of PrintWriter and Lines 22-24 are create the XHTML document by writing strings with the out
object’s println method.
The XHTML document below provides a form that invokes the servlet defined above. The form’s action
specifies the URL path that invokes the servlet, and the form’s method indicates that the browser sends a get
request to the server, which results in a call to the servlet’s doGet method.

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 <!-- 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 = "welcome1" method = "get">
14
15 <p><label>Click the button to invoke the servlet
16 <input type = "submit" value = "Get HTML Document" />
17 </label></p>

Page 8
Java Servlet Technology
18
19 </form>
20 </body>
21 </html>
22
Figure 3: HTML document in which the form’s action invokes WelcomeServlet through the alias
welcome1

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 of Figure-4 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.
1 // WelcomeServlet2.java
2 // Processing HTTP get requests containing data.
3
4
5 import javax.servlet.*;
6 import javax.servlet.http.*;
7 import java.io.*;
8
9 public class WelcomeServlet2 extends HttpServlet {
10
11 // process "get" request from client
12 protected void doGet( HttpServletRequest request,
13 HttpServletResponse response )
14 throws ServletException, IOException
15 {
16 String firstName = request.getParameter( "firstname" );
17
18 response.setContentType( "text/html" );
19 PrintWriter out = response.getWriter();
20
21 // send XHTML document to client
22
23 // start XHTML document
24 out.println( "<?xml version = \"1.0\"?>" );
25
26 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
27 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
28 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
29
30 out.println(
31 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
32
33 // head section of document
34 out.println( "<head>" );
35 out.println(
36 "<title>Processing get requests with data</title>" );
37 out.println( "</head>" );
38
39 // body section of document
40 out.println( "<body>" );
41 out.println( "<h1>Hello " + firstName + ",<br />" );
42 out.println( "Welcome to Servlets!</h1>" );
43 out.println( "</body>" );
44

Page 9
Java Servlet Technology
45 // end XHTML document
46 out.println( "</html>" );
47 out.close(); // close stream to complete the page
48 }
49 }
Figure-4: WelcomeServlet2 responds to a get request that contains data

Parameters are passed as name/value pairs in a get request. Line 16 demonstrates how to obtain information that
was passed to the servlet as part of the client request. The request object’s getParameter method receives
the parameter name as an argument and returns the corresponding String value, or null if the parameter is
not part of the request. Line 41 uses the result of line 16 as part of the response to the client.
The WelcomeServlet2.html document (Figure-5) provides a form in which the user can input a name in the
text input element firstname (line 17) 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.
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 <!--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 = "welcome2" method = "get">
14
15 <p><label>
16 Type your first name and press the Submit button
17 <br /><input type = "text" name = "firstname" />
18 <input type = "submit" value = "Submit" />
19 </p></label>
20
21 </form>
22 </body>
23 </html>
24
Figure-5: HTML document in which the form’s action invokes WelcomeServlet2 through the
alias welcome2

In get request, data, in form of name/value pair, is appended in URL separated by ?. This added string is called
query string. The name/value pairs are passed with the name and the value separated by =. If there is more than
one name/value pair, each name/value pair is separated by &.

Handling HTTP post Requests


An HTTP post request is often used to post data from an HTML form to a server-side form handler that processes
the data. For example, when you respond to a Web-based survey, a post request normally supplies the information
you specify in the HTML form to the Web server.
Browsers often cache (save on disk) Web pages so they can quickly reload the pages. If there are no changes
between the last version stored in the cache and the current version on the Web, this helps speed up your
browsing experience. The browser first asks the server if the document has changed or expired since the date the
file was cached. If not, the browser loads the document from the cache. Thus, the browser minimizes the amount

Page 10
Java Servlet Technology
of data that must be downloaded for you to view a Web page. Browsers typically do not cache the server’s
response to a post request, because the next post might not return the same result.
As with post requests, get requests can supply parameters as part of the request to the Web server. The
WelcomeServlet3 servlet of Figure-6 is identical to the servlet of Figure-2, except that it defines a doPost
method (line 12) to respond to post requests rather than a doGet method. The default functionality of doPost is
to indicate a “Method not allowed” error. We override this method to provide custom post request processing.
Method doPost receives the same two arguments as doGet—an object that implements interface
HttpServletRequest to represent the client’s request and an object that implements interface
HttpServletResponse to represent the servlet’s response. As with doGet, method doPost throws a
ServletException if it is unable to handle a client’s request and throws an IOException if a problem
occurs during stream processing.
1 // WelcomeServlet3.java
2 // Processing post requests containing data.
3
4
5 import javax.servlet.*;
6 import javax.servlet.http.*;
7 import java.io.*;
8
9 public class WelcomeServlet3 extends HttpServlet {
10
11 // process "post" request from client
12 protected void doPost( HttpServletRequest request,
13 HttpServletResponse response )
14 throws ServletException, IOException
15 {
16 String firstName = request.getParameter( "firstname" );
17
18 response.setContentType( "text/html" );
19 PrintWriter out = response.getWriter();
20
21 // send XHTML page to client
22
23 // start XHTML document
24 out.println( "<?xml version = \"1.0\"?>" );
25
26 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
27 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
28 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
29
30 out.println(
31 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
32
33 // head section of document
34 out.println( "<head>" );
35 out.println(
36 "<title>Processing post requests with data</title>" );
37 out.println( "</head>" );
38
39 // body section of document
40 out.println( "<body>" );
41 out.println( "<h1>Hello " + firstName + ",<br />" );
42 out.println( "Welcome to Servlets!</h1>" );
43 out.println( "</body>" );
44
45 // end XHTML document
46 out.println( "</html>" );

Page 11
Java Servlet Technology
47 out.close(); // close stream to complete the page
48 }
49 }
Figure-6: WelcomeServlet3 responds to a post request that contains data

WelcomeServlet3.html (Figure-7) provides a form (lines 13–21) in which the user can input a name in the
text input element firstname (line 17), then click the Submit button to invoke WelcomeServlet3. When
the user presses the Submit button, the values of the input elements are sent to the server as part of the
request. However, note that the values are not appended to the request URL. Note that the form’s method in this
example is post. Also, note that a post request cannot be typed into the browser’s Address or Location field and
users cannot bookmark post requests in their browsers.
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 <!--WelcomeServlet3.html -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Handling an HTTP Post Request with Data</title>
10 </head>
11
12 <body>
13 <form action = "welcome3" method = "post">
14
15 <p><label>
16 Type your first name and press the Submit button
17 <br /><input type = "text" name = "firstname" />
18 <input type = "submit" value = "Submit" />
19 </label></p>
20
21 </form>
22 </body>
23 </html>
Figure-7: HTML document in which the form’s action invokes WelcomeServlet3 through the
alias welcome3

Redirecting Requests to Other Resources


Sometimes it is useful to redirect a request to a different resource. For example, a servlet could determine the type
of the client browser and redirect the request to a Web page that was designed specifically for that browser. The
sendRedirect method of javax.servlet.http.HttpServletResponse class can be used. The
general form of this method is:
void sendRedirect(String location)throws IOException
This method sends a temporary redirect response to the client using the specified redirect location URL. This
method can accept relative URLs; the servlet container must convert the relative URL to an absolute URL before
sending the response to the client. If the location is relative without a leading '/' the container interprets it as
relative to the current request URI. If the location is relative with a leading '/' the container interprets it as relative
to the servlet container root.
The RedirectServlet of Figure-8 receives a page parameter as part of a get request, then uses that parameter
to redirect the request to a different resource.
1 // RedirectServlet.java
2 // Redirecting a user to a different Web page.
3

Page 12
Java Servlet Technology
4
5 import javax.servlet.*;
6 import javax.servlet.http.*;
7 import java.io.*;
8
9 public class RedirectServlet extends HttpServlet {
10
11 // process "get" request from client
12 protected void doGet( HttpServletRequest request,
13 HttpServletResponse response )
14 throws ServletException, IOException
15 {
16 String location = request.getParameter( "page" );
17
18 if ( location != null )
19
20 if ( location.equals( "deitel" ) )
21 response.sendRedirect( "http://www.deitel.com" );
22 else
23 if ( location.equals( "welcome1" ) )
24 response.sendRedirect( "welcome1" );
25
26 // code that executes only if this servlet
27 // does not redirect the user to another page
28
29 response.setContentType( "text/html" );
30 PrintWriter out = response.getWriter();
31
32 // start XHTML document
33 out.println( "<?xml version = \"1.0\"?>" );
34
35 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
36 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
37 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
38
39 out.println(
40 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
41
42 // head section of document
43 out.println( "<head>" );
44 out.println( "<title>Invalid page</title>" );
45 out.println( "</head>" );
46
47 // body section of document
48 out.println( "<body>" );
49 out.println( "<h1>Invalid page requested</h1>" );
50 out.println( "<p><a href = " +
51 "\"servlets/RedirectServlet.html\">" );
52 out.println( "Click here to choose again</a></p>" );
53 out.println( "</body>" );
54
55 // end XHTML document
56 out.println( "</html>" );
57 out.close(); // close stream to complete the page
58 }
59 }
Figure-8: Redirecting requests to other resources

Page 13
Java Servlet Technology
Line 16 obtains the page parameter from the request. If the value returned is not null, the if/else structure
at lines 20–24 determines if the value is either “deitel” or “welcome1.” If the value is “deitel,” the response
object’s sendRedirect method (line 21) redirects the request to www.deitel.com. If the value is “welcome1,”
line 24 redirects the request to the servlet of Figure-2. When a servlet uses a relative path to reference another
static or dynamic resource, the servlet assumes the same base URL and context root as the one that invoked the
servlet—unless a complete URL is specified for the resource.
Once method sendRedirect executes, processing of the original request by the RedirectServlet
terminates. If method sendRedirect is not called, the remainder of method doGet outputs a Web page
indicating that an invalid request was made.
The RedirectServlet.html document (Figure-9) provides two hyperlinks (lines 15–16 and 17–18) that allow
the user to invoke the servlet RedirectServlet. Note that each hyperlink specifies a page parameter as part
of the URL. To demonstrate passing an invalid page, you can type the URL into your browser with no value for the
page parameter.
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 <!--RedirectServlet.html -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Redirecting a Request to Another Site</title>
10 </head>
11
12 <body>
13 <p>Click a link to be redirected to the appropriate page</p>
14 <p>
15 <a href = "/advjhtp1/redirect?page=deitel">
16 www.deitel.com</a><br />
17 <a href = "/advjhtp1/redirect?page=welcome1">
18 Welcome servlet</a>
19 </p>
20 </body>
21 </html>
Figure-9: RedirectServlet.html document to demonstrate redirecting requests to other
resources.
When redirecting requests, the request parameters from the original request are passed as parameters to the new
request. Additional request parameters also can be passed. For example, the URL passed to sendRedirect could
contain name/value pairs. Any new parameters are added to the existing parameters. If a new parameter has the
same name as an existing parameter, the new parameter value takes precedence over the original value. However,
all the values are still passed. In this case, the complete set of values for a given parameter name can be obtained
by calling method getParameterValues from interface HttpServletRequest. This method receives the
parameter name as an argument and returns an array of Strings containing the parameter values in order from
most recent to least recent.

Session Tracking
HTTP is a stateless protocol: it provides no way for a server to recognize that a sequence of requests is all from the
same client. Privacy advocates may consider this a feature, but it causes problems because many web applications
aren’t stateless. The shopping cart application is a classic example—a client can put items in his virtual cart,
accumulating them until he checks out several page requests later. Other examples include sites that offer stock
brokerage services or interactive data mining. One solution for this is to maintain a session per user during each
transaction.

Page 14
Java Servlet Technology
A Session refers to all the requests that a single client makes to a server. A session is specific to the user and for
each user a new session is created to track all the requests from that user. Every user has a separate session and
separate session variable is associated with that session. In case of web applications the default time-out value for
session variable is 20 minutes, which can be changed as per the requirement.
A session ID is a unique identification string usually a long, random and alpha-numeric string that is transmitted
between the client and the server. Session IDs are usually stored in the cookies, URLs (in case URL rewriting) and
hidden fields of Web pages.
Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user
(that is, requests originating from the same browser) across some period of time. Sessions are shared among the
servlets accessed by a client. This is convenient for applications made up of multiple servlets.
Mechanisms for session tracking are:
1. Cookies
2. Session tracking with HttpSession
3. Hidden field
4. URL Rewriting

Cookies
A cookie is a bit of information sent by a web server to a browser that can later be read back from that browser.
When a browser receives a cookie, it saves the cookie and thereafter sends the cookie back to the server each time
it accesses a page on that server, subject to certain rules. Because a cookie’s value can uniquely identify a client,
cookies are often used for session tracking.
There are two types of cookies: session cookie and persistent cookie. Session cookies are temporary cookie files,
which are erased when you close your browser. When you restart your browser and go back to the site that
created the cookie, the website will not recognize you. You will have to log back in (if login is required) or select
your preferences/themes again if the site uses these features. A new session cookie will be generated, which will
store your browsing information and will be active until you leave the site and close your browser. Persistent
cookies stay in one of your browser's subfolders until you delete them manually or your browser deletes them
based on the duration period contained within the persistent cookie's file
Cookies are text-based data that are sent by servlets (or other similar server-side technologies) as part of responses
to clients. Every HTTP-based interaction between a client and a server includes a header containing information
about the request (when the communication is from the client to the server) or information about the response
(when the communication is from the server to the client). When an HttpServlet receives a request, the
header includes information such as the request type (e.g., get or post) and the cookies that are sent by the server
to be stored on the client machine. When the server formulates its response, the header information includes any
cookies the server wants to store on the client computer and other information such as the MIME type of the
response.
Depending on the maximum age of a cookie, the Web browser either maintains the cookie for the duration of the
browsing session (i.e., until the user closes the Web browser) or stores the cookie on the client computer for future
use. When the browser requests a resource from a server, cookies previously sent to the client by that server are
returned to the server as part of the request formulated by the browser. Cookies are deleted automatically when
they expire (i.e., reach their maximum age).
The example allows the user to select a favourite programming language and post the choice to the server. The
response is a Web page in which the user can select another favourite language or click a link to view a list of book
recommendations. When the user selects the list of book recommendations, a get request is sent to the server. The
cookies previously stored on the client are read by the servlet and used to form a Web page containing the book
recommendations.
CookieServlet (Figure-10) handles both the get and the post requests. The CookieSelectLanguage.html
document of Figure-11 contains four radio buttons (C, C++, Java and VB 6) and a Submit button. When the user
presses Submit, the CookieServlet is invoked with a post request. The servlet adds a cookie containing the

Page 15
Java Servlet Technology
selected language to the response header and sends an XHTML document to the client. Each time the user clicks
Submit, a cookie is sent to the client.

1 // CookieServlet.java
2 // Using cookies to store data on the client computer.
3
4
5 import javax.servlet.*;
6 import javax.servlet.http.*;
7 import java.io.*;
8 import java.util.*;
9
10 public class CookieServlet extends HttpServlet {
11 private final Map books = new HashMap();
12
13 // initialize Map books
14 public void init()
15 {
16 books.put( "C", "0130895725" );
17 books.put( "C++", "0130895717" );
18 books.put( "Java", "0130125075" );
19 books.put( "VB6", "0134569555" );
20 }
21
22 // receive language selection and send cookie containing
23 // recommended book to the client
24 protected void doPost( HttpServletRequest request,
25 HttpServletResponse response )
26 throws ServletException, IOException
27 {
28 String language = request.getParameter( "language" );
29 String isbn = books.get( language ).toString();
30 Cookie cookie = new Cookie( language, isbn );
31
32 response.addCookie( cookie ); // must precede getWriter
33 response.setContentType( "text/html" );
34 PrintWriter out = response.getWriter();
35
36 // send XHTML page to client
37
38 // start XHTML document
39 out.println( "<?xml version = \"1.0\"?>" );
40
41 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
42 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
43 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
44
45 out.println(
46 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
47
48 // head section of document
49 out.println( "<head>" );
50 out.println( "<title>Welcome to Cookies</title>" );
51 out.println( "</head>" );
52

Page 16
Java Servlet Technology
53 // body section of document
54 out.println( "<body>" );
55 out.println( "<p>Welcome to Cookies! You selected " +
56 language + "</p>" );
57
58 out.println( "<p><a href = " +
59 "\"/CookieSelectLanguage.html\">" +
60 "Click here to choose another language</a></p>" );
61
62 out.println( "<p><a href = \"/advjhtp1/cookies\">" +
63 "Click here to get book recommendations</a></p>" );
64 out.println( "</body>" );
65
66 // end XHTML document
67 out.println( "</html>" );
68 out.close(); // close stream
69 }
70
71 // read cookies from client and create XHTML document
72 // containing recommended books
73 protected void doGet( HttpServletRequest request,
74 HttpServletResponse response )
75 throws ServletException, IOException
76 {
77 Cookie cookies[] = request.getCookies(); // get cookies
78
79 response.setContentType( "text/html" );
80 PrintWriter out = response.getWriter();
81
82 // start XHTML document
83 out.println( "<?xml version = \"1.0\"?>" );
84
85 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
86 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
87 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
88
89 out.println(
90 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
91
92 // head section of document
93 out.println( "<head>" );
94 out.println( "<title>Recommendations</title>" );
95 out.println( "</head>" );
96
97 // body section of document
98 out.println( "<body>" );
99
100 // if there are any cookies, recommend a book for each ISBN
101 if ( cookies != null && cookies.length != 0 ) {
102 out.println( "<h1>Recommendations</h1>" );
103 out.println( "<p>" );
104
105 // get the name of each cookie
106 for ( int i = 0; i < cookies.length; i++ )
107 out.println( cookies[ i ].getName() +
108 " How to Program. ISBN#: " +
109 cookies[ i ].getValue() + "<br />" );
110
111 out.println( "</p>" );

Page 17
Java Servlet Technology
112 }
113 else { // there were no cookies
114 out.println( "<h1>No Recommendations</h1>" );
115 out.println( "<p>You did not select a language.</p>" );
116 }
117
118 out.println( "</body>" );
119
120 // end XHTML document
121 out.println( "</html>" );
122 out.close(); // close stream
123 }
124 }
Figure-10: Storing user data on the client computer with cookies

Line 30 creates a new Cookie object (package javax.servlet.http), using the language and isbn values as
the cookie name and cookie value, respectively. The cookie name identifies the cookie; the cookie value is the
information associated with the cookie. Browsers that support cookies must be able to store a minimum of 20
cookies per Web site and 300 cookies per user. Browsers may limit the cookie size to 4K (4096 bytes). Each cookie
stored on the client includes a domain. The browser sends a cookie only to the domain stored in the cookie.
Line 32 adds the cookie to the response with method addCookie of interface HttpServletResponse.
Cookies are sent to the client as part of the HTTP header. The header information is always provided to the client
first, so the cookies should be added to the response with addCookie before any data is written as part of the
response. After the cookie is added, the servlet sends an XHTML document to the client.
Line 77 retrieves the cookies from the client using HttpServletRequest method getCookies, which returns
an array of Cookie objects. When a get or post operation is performed to invoke a servlet, the cookies associated
with that server’s domain are automatically sent to the servlet. If method getCookies does not return null
(i.e., there were no cookies), lines 106–109 retrieve the name of each Cookie using Cookie method getName,
retrieve the value of each Cookie using Cookie method getValue and write a line to the client indicating the
name of a recommended book and its ISBN number.
Figure-11 shows the XHTML document the user loads to select a language. When the user presses Submit, the
value of the currently selected radio button is sent to the server as part of the post request to the
CookieServlet, which we refer to as cookies in this example.
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 <!--CookieSelectLanguage.html -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Using Cookies</title>
10 </head>
11
12 <body>
13 <form action = "/advjhtp1/cookies" method = "post">
14
15 <p>Select a programming language:</p>
16 <p>
17 <input type = "radio" name = "language"
18 value = "C" />C <br />
19
20 <input type = "radio" name = "language"
21 value = "C++" />C++ <br />
22

Page 18
Java Servlet Technology
23 <!-- this radio button checked by default -->
24 <input type = "radio" name = "language"
25 value = "Java" checked = "checked" />Java<br />
26
27 <input type = "radio" name = "language"
28 value = "VB6" />VB 6
29 </p>
30
31 <p><input type = "submit" value = "Submit" /></p>
32
33 </form>
34 </body>
35 </html>
Figure-11: CookieSelectLanguage.html document for selecting a programming language and
posting the data to the CookieServlet

Various Cookie methods are provided to manipulate the members of a Cookie. Some of these methods are
listed below:

Method Description

public String getComment()

Returns a String describing the purpose of the cookie (null if no comment has been set with
setComment).

public String getDomain()

Returns a String containing the cookie’s domain. This determines which servers can receive the
cookie. By default, cookies are sent to the server that originally sent the cookie to the client.

public int getMaxAge()

Returns an int representing the maximum age of the cookie in seconds. By default, -1 indicating the
cookie will persist until browser shutdown.

public String getName()

Returns a String containing the name of the cookie as set by the constructor.
public String getPath()
Returns a String containing the URL prefix for the cookie. Cookies can be “targeted” to specific
URLs that include directories on the Web server. By default, a cookie is returned to services operating
in the same directory as the service that sent the cookie or a subdirectory of that directory.
public boolean getSecure()
Returns a boolean value indicating if the cookie should be transmitted using a secure protocol
(true).
public String getValue()
Returns a String containing the value of the cookie as set with setValue or the constructor.
public int getVersion()
Returns an int containing the version of the cookie protocol used to create the cookie. A value of 0
(the default) indicates the original cookie protocol as defined by Netscape. A value of 1 indicates the
current version, which is based on Request for Comments (RFC) 2109.
public void setComment(String purpose)

Page 19
Java Servlet Technology
The comment describing the purpose of the cookie that is presented by the browser to the user.
(Some browsers allow the user to accept cookies on a per-cookie basis.)
public void setDomain(String pattern)
This determines which servers can receive the cookie. By default, cookies are sent to the server that
originally sent the cookie to the client. The domain is specified in the form ".deitel.com", indicating
that all servers ending with .deitel.com can receive this cookie.
public void setMaxAge(int expiry)
Sets the maximum age of the cookie in seconds. A positive value indicates that the cookie will expire
after that many seconds have passed. Note that the value is the maximum age when the cookie will
expire, not the cookie's current age.
A negative value means that the cookie is not stored persistently and will be deleted when the Web
browser exits. A zero value causes the cookie to be deleted.
public void setPath(String uri)
Sets the “target” URL prefix indicating the directories on the server that lead to the services that can
receive this cookie. The cookie is visible to all the pages in the directory you specify, and all the pages
in that directory's subdirectories. A cookie's path must include the servlet that set the cookie, for
example, /catalog, which makes the cookie visible to all directories on the server under /catalog.
public void setSecure(boolean flag)
A true value indicates that the cookie should only be sent using a secure protocol. The default value
is false.

public void setValue(String newValue)


Assigns a new value to a cookie after the cookie is created. If you use a binary value, you may want to
use BASE64 encoding.
With Version 0 cookies, values should not contain white space, brackets, parentheses, equals signs,
commas, double quotes, slashes, question marks, at signs, colons, and semicolons. Empty values may
not behave the same way on all browsers.
public void setVersion(int v)
Sets the version of the cookie protocol this cookie complies with. Version 0 complies with the original
Netscape cookie specification. Version 1 complies with RFC 2109.
Since RFC 2109 is still somewhat new, consider version 1 as experimental; do not use it yet on
production sites.

Session Tracking with HttpSession


Java provides enhanced session tracking support with the servlet API’s HttpSession interface. Sessions are
represented by an HttpSession object. You access a session by calling the
HttpServletRequest.getSession() or HttpServletRequest.getSession(boolean) method
of a request object. This method returns the current session associated with this request, or, if the request does
not have a session, it creates one (unless boolean argument is false). A false argument would cause method
getSession to return null if the HttpSession object for the client did not already exist. Using a false
argument could help determine whether a client has logged into a Web application.
You can associate object-valued attributes with a session by name. Such attributes are accessible by any Web
component that belongs to the same Web context and is handling a request that is part of the same session. The
attributes are placed into an HttpSession object with method setAttribute.

Page 20
Java Servlet Technology
Name/value pairs added to an HttpSession object with setAttribute remain available until the client’s
current browsing session ends or until the session is invalidated explicitly by a call to the HttpSession object’s
invalidate method. Also, if the servlet container is restarted, these attributes may be lost.
We modified the servlet from Figure-10 to use HttpSession objects (Figure-12). Once again, the servlet handles
both get and post requests. The document SessionSelectLanguage.html of Figure-13 contains four radio
buttons (C, C++, Java and VB 6) and a Submit button. When the user presses Submit, SessionServlet is
invoked with a post request. The servlet responds by creating an object of type HttpSession for the client (or
using an existing session for the client) and adds the selected language and an ISBN number for the recommended
book to the HttpSession object. Then, the servlet sends an XHTML page to the client. Each time the user clicks
Submit, a new language/ISBN pair is added to the HttpSession object.
1 // SessionServlet.java
2 // Using HttpSession to maintain client state information.
3
4
5 import javax.servlet.*;
6 import javax.servlet.http.*;
7 import java.io.*;
8 import java.util.*;
9
10 public class SessionServlet extends HttpServlet {
11 private final Map books = new HashMap();
12
13 // initialize Map books
14 public void init()
15 {
16 books.put( "C", "0130895725" );
17 books.put( "C++", "0130895717" );
18 books.put( "Java", "0130125075" );
19 books.put( "VB6", "0134569555" );
20 }
21
22 // receive language selection and create HttpSession object
23 // containing recommended book for the client
24 protected void doPost( HttpServletRequest request,
25 HttpServletResponse response )
26 throws ServletException, IOException
27 {
28 String language = request.getParameter( "language" );
29
30 // Get the user's session object.
31 // Create a session (true) if one does not exist.
32 HttpSession session = request.getSession( true );
33
34 // add a value for user's choice to session
35 session.setAttribute( language, books.get( language ) );
36
37 response.setContentType( "text/html" );
38 PrintWriter out = response.getWriter();
39
40 // send XHTML page to client
41
42 // start XHTML document
43 out.println( "<?xml version = \"1.0\"?>" );
44
45 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
46 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
47 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );

Page 21
Java Servlet Technology
48
49 out.println(
50 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
51
52 // head section of document
53 out.println( "<head>" );
54 out.println( "<title>Welcome to Sessions</title>" );
55 out.println( "</head>" );
56
57 // body section of document
58 out.println( "<body>" );
59 out.println( "<p>Welcome to Sessions! You selected " +
60 language + ".</p>" );
61
62 // display information about the session
63 out.println( "<p>Your unique session ID is: " +
64 session.getId() + "<br />" );
65
66 out.println(
67 "This " + ( session.isNew() ? "is" : "is not" ) +
68 " a new session<br />" );
69
70 out.println( "The session was created at: " +
71 new Date( session.getCreationTime() ) + "<br />" );
72
73 out.println( "You last accessed the session at: " +
74 new Date( session.getLastAccessedTime() ) + "<br />" );
75
76 out.println( "The maximum inactive interval is: " +
77 session.getMaxInactiveInterval() + " seconds</p>" );
78
79 out.println( "<p><a href = " +
80 "\"servlets/SessionSelectLanguage.html\">" +
81 "Click here to choose another language</a></p>" );
82
83 out.println( "<p><a href = \"sessions\">" +
84 "Click here to get book recommendations</a></p>" );
85 out.println( "</body>" );
86
87 // end XHTML document
88 out.println( "</html>" );
89 out.close(); // close stream
90 }
91
92 // read session attributes and create XHTML document
93 // containing recommended books
94 protected void doGet( HttpServletRequest request,
95 HttpServletResponse response )
96 throws ServletException, IOException
97 {
98 // Get the user's session object.
99 // Do not create a session (false) if one does not exist.
100 HttpSession session = request.getSession( false );
101
102 // get names of session object's values
103 Enumeration valueNames;
104
105 if ( session != null )
106 valueNames = session.getAttributeNames();

Page 22
Java Servlet Technology
107 else
108 valueNames = null;
109
110 PrintWriter out = response.getWriter();
111 response.setContentType( "text/html" );
112
113 // start XHTML document
114 out.println( "<?xml version = \"1.0\"?>" );
115
116 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
117 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
118 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
119
120 out.println(
121 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
122
123 // head section of document
124 out.println( "<head>" );
125 out.println( "<title>Recommendations</title>" );
126 out.println( "</head>" );
127
128 // body section of document
129 out.println( "<body>" );
130
131 if ( valueNames != null &&
132 valueNames.hasMoreElements() ) {
133 out.println( "<h1>Recommendations</h1>" );
134 out.println( "<p>" );
135
136 String name, value;
137
138 // get value for each name in valueNames
139 while ( valueNames.hasMoreElements() ) {
140 name = valueNames.nextElement().toString();
141 value = session.getAttribute( name ).toString();
142
143 out.println( name + " How to Program. " +
144 "ISBN#: " + value + "<br />" );
145 }
146
147 out.println( "</p>" );
148 }
149 else {
150 out.println( "<h1>No Recommendations</h1>" );
151 out.println( "<p>You did not select a language.</p>" );
152 }
153
154 out.println( "</body>" );
155
156 // end XHTML document
157 out.println( "</html>" );
158 out.close(); // close stream
159 }
160 }
Figure-12: Maintaining state information with HttpSession objects

The line 32 uses method getSession of interface HttpServletRequest to obtain the HttpSession
object for the client. If the server has an existing HttpSession object for the client from a previous request,

Page 23
Java Servlet Technology
method getSession returns that HttpSession object. Otherwise, the true argument to method
getSession indicates that the servlet should create a unique new HttpSession object for the client.
Like a cookie, an HttpSession object can store name/value pairs. In session terminology, these are called
attributes. Line 35 uses setAttribute to put the language and the corresponding recommended book’s ISBN
number into the HttpSession object. One of the primary benefits of using HttpSession objects rather than
cookies is that HttpSession objects can store any object (not just Strings) as the value of an attribute. This
allows Java programmers flexibility in determining the type of state information they wish to maintain for clients of
their Web applications. If an attribute with a particular name already exists when setAttribute is called, the
object associated with that attribute name is replaced.
After the values are added to the HttpSession object, the servlet sends an XHTML document to the client. In
this example, the document contains various information about the HttpSession object for the current client.
Line 64 uses HttpSession method getID to obtain the session’s unique ID number. Line 67 determines
whether the session is new or already exists with method isNew, which returns true or false. Line 71 obtains
the time at which the session was created with method getCreationTime. Line 74 obtains the time at which the
session was last accessed with method getLastAccessedTime. Line 77 uses method
getMaxInactiveInterval to obtain the maximum amount of time that an HttpSession object can be
inactive before the servlet container discards it.
The XHTML document sent to the client in response to a post request includes a hyperlink that invokes method
doGet (lines 94–159). The method obtains the HttpSession object for the client with method getSession
(line 100). We do not want to make any recommendations if the client does not have an existing HttpSession
object. So, this call to getSession uses a false argument. Thus, getSession returns an HttpSession
object only if one already exists for the client. If method getSession does not return null, line 106 uses
HttpSession method getAttributeNames to retrieve an Enumeration of the attribute names (i.e., the
names used as the first argument to HttpSession method setAttribute). Each name is passed as an
argument to HttpSession method getAttribute (line 141) to retrieve the ISBN of a book from the
HttpSession object. Method getAttribute receives the name and returns an Object reference to the
corresponding value. Next, a line is written in the response to the client containing the title and ISBN number of the
recommended book.
Figure-13 shows the XHTML document the user loads to select a language. When the user presses Submit, the
value of the currently selected radio button is sent to the server as part of the post request to the
SessionServlet, which we refer to as sessions in this example.
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 <!--SessionSelectLanguage.html -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Using Sessions</title>
10 </head>
11
12 <body>
13 <form action = "/advjhtp1/sessions" method = "post">
14
15 <p>Select a programming language:</p>
16 <p>
17 <input type = "radio" name = "language"
18 value = "C" />C <br />
19
20 <input type = "radio" name = "language"
21 value = "C++" />C++ <br />
22
23 <!-- this radio button checked by default -->

Page 24
Java Servlet Technology
24 <input type = "radio" name = "language"
25 value = "Java" checked = "checked" />Java<br />
26
27 <input type = "radio" name = "language"
28 value = "VB6" />VB 6
29 </p>
30
31 <p><input type = "submit" value = "Submit" /></p>
32
33 </form>
34 </body>
35 </html>
Figure-13: SessionSelectLanguage.html document for selecting a programming language and
posting the data to the SessionServlet

Hidden Fields
One way to support anonymous session tracking is to use hidden form fields. As the name implies, these are fields
added to an HTML form that are not displayed in the client's browser. They are sent back to the server when the
form that contains them is submitted. You include hidden form fields with HTML like this:
<FORM ACTION="/servlet/MovieFinder" METHOD="POST">
...
<INPUT TYPE=hidden NAME="zip" VALUE="94040">
<INPUT TYPE=hidden NAME="level" VALUE="expert">
...
</FORM>
In a sense, hidden form fields define constant variables for a form. To a servlet receiving a submitted form, there is
no difference between a hidden field and a visible field.
As more and more information is associated with a client's session, it can become burdensome to pass it all using
hidden form fields. In these situations, it's possible to pass on just a unique session ID that identifies a particular
client's session. That session ID can be associated with complete information about the session that is stored on the
server.
The advantages of hidden form fields are their ubiquity and support for anonymity. Hidden fields are supported in
all the popular browsers, they demand no special server requirements, and they can be used with clients that
haven't registered or logged in. The major disadvantage with this technique, however, is that it works only for a
sequence of dynamically generated forms. The technique breaks down immediately with static documents, emailed
documents, bookmarked documents, and browser shutdowns.

URL Rewriting
URL Rewriting is used foe session management. If we use cookies for session management but it is possible that
some time user may block the cookies, and because if this server cannot also maintain the session, therefore, we
use URL Rewriting as a backup for the session management.
URL rewriting involves adding data, a session ID, to the URL path that is interpreted by the container to associate
the request with a session. The session ID must be encoded as a path parameter in the URL string. Here is an
example of a URL containing encoded path information:
http://www.myserver.com/catalog/index.html;jsessionid=1234
There are 2 methods in the HttpServletResponse for URL rewriting:
• encodeURL(String)
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL
unchanged. The implementation of this method includes the logic to determine whether the session ID
needs to be encoded in the URL. For example, if the browser supports cookies, or session tracking is turned
off, URL encoding is unnecessary. For robust session tracking, all URLs emitted by a servlet should be run

Page 25
Java Servlet Technology
through this method. Otherwise, URL rewriting cannot be used with browsers which do not support
cookies.

• encodeRedirectURL(String)
Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns
the URL unchanged. The implementation of this method includes the logic to determine whether the
session ID needs to be encoded in the URL. Because the rules for making this determination can differ from
those used to decide whether to encode a normal link, this method is separated from
the encodeURL method. All URLs sent to the HttpServletResponse.sendRedirect method
should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not
support cookies.

Dispatching Request
When building a Web application, it is often useful to forward processing of a request to another servlet, or to
include the output of another servlet in the response. The RequestDispatcher interface provides a
mechanism to accomplish this.
RequestDispatcher defines an object that receives requests from the client and sends them to any resource
(such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher
object, which is used as a wrapper around a server resource located at a particular path or given by a particular
name.
An object implementing the RequestDispatcher interface may be obtained via the following methods:
• ServletContext.getRequestDispatcher(String path)
• ServletContext.getNamedDispatcher(String name)
• ServletRequest.getRequestDispatcher(String path)
The ServletContext.getRequestDispatcher method takes a String argument describing a path
within the scope of the ServletContext. This path must be relative to the root of the ServletContext and
begin with a '/'. The method uses the path to look up a servlet, using the servlet path matching rules, wraps it with
a RequestDispatcher object, and returns the resulting object. If no servlet can be resolved based on the given
path, a RequestDispatcher is provided that returns the content for that path.
The ServletContext.getNamedDispatcher method takes a String argument indicating the NAME of a
servlet known to the ServletContext. If a servlet is found, it is wrapped with a RequestDispatcher object
and the object is returned. If no servlet is associated with the given name, the method must return null.
The ServletRequest.getRequestDispatcher method is provided in the ServletRequest interface.
The behavior of this method is similar to the method of the same name in the ServletContext. The servlet
container uses information in the request object to transform the given relative path against the current servlet to
a complete path. For example, in a context rooted at '/' and a request to /garden/tools.html, a request dispatcher
obtained via ServletRequest.getRequestDispatcher("header.html") will behave exactly like a
call to ServletContext.getRequestDispatcher("/garden/header.html").
To use a request dispatcher, a servlet calls either the include method or forward method of the
RequestDispatcher interface. The parameters to these methods are the request and response arguments
that were passed in via the service method of the javax.servlet interface.

The include Method


This method includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this
method enables programmatic server-side includes.

Page 26
Java Servlet Technology
The include method of the RequestDispatcher interface may be called at any time. The target servlet of
the include method has access to all aspects of the request object, but its use of the response object is more
limited.
It can only write information to the ServletOutputStream or Writer of the response object and commit a
response by writing content past the end of the response buffer, or by explicitly calling the flushBuffer method
of the ServletResponse interface. It cannot set headers or call any method that affects the headers of the
response. Any attempt to do so must be ignored.
It CANNOT set headers or call any method that affects the headers of the response. Any attempt to do so must be
ignored.
Except for servlets obtained by using the getNamedDispatcher method, a servlet that has been invoked by
another servlet using the include method of RequestDispatcher has access to the path by which it was
invoked.
The following request attributes must be set:
javax.servlet.include.request_uri
javax.servlet.include.context_path
javax.servlet.include.servlet_path
javax.servlet.include.path_info
javax.servlet.include.query_string
These attributes are accessible from the included servlet via the getAttribute method on the request object
and their values must be equal to the request URI, context path, servlet path, path info, and query string of the
included servlet, respectively. If the request is subsequently included, these attributes are replaced for that include.

The forward Method


This method forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
This method allows one servlet to do preliminary processing of a request and another resource to generate the
response.
The forward method of the RequestDispatcher interface may be called by the calling servlet only when no
output has been committed to the client. If output data exists in the response buffer that has not been committed,
the content must be cleared before the target servlet’s service method is called. If the response has been
committed, an IllegalStateException must be thrown. Before the forward method of the
RequestDispatcher interface returns, the response content must be sent and committed, and closed by the
servlet container.
Except for servlets obtained by using the getNamedDispatcher method, a servlet that has been invoked by
another servlet using the forward method of RequestDispatcher has access to the path of the original
request.
The following request attributes must be set:
javax.servlet.forward.request_uri
javax.servlet.forward.context_path
javax.servlet.forward.servlet_path
javax.servlet.forward.path_info
javax.servlet.forward.query_string
The values of these attributes must be equal to the return values of the HttpServletRequest methods
getRequestURI, getContextPath, getServletPath, getPathInfo, getQueryString respectively,
invoked on the request object passed to the first servlet object in the call chain that received the request from the
client. These attributes are accessible from the forwarded servlet via the getAttribute method on the request
object.

Page 27