Java_week_14
Java_week_14
Names of Sub-Units
Servlets: Background, The Life Cycle of a Servlet, Using Tomcat for Servlet Development, A simple
Servlet, The Servlet API, The Javax.servlet Package, Reading Servlet Parameter; The Javax.servlet.
http package; Handling HTTP Requests and Responses, Working with Cookies, Session Tracking,
Java Server Pages (JSP): Introduction, JSP Tags, Using Tomcat for JSP, Request String, User Sessions,
Cookies, Session Objects
Overview
The unit first explores the general features of Java Servlet, after which you learn about the features
of the latest version of Java Servlet, i.e., 3.1. Next, the unit explains the classes and packages of the
Servlet Application Programming Interface (API) used to develop Web applications. You also learn
about the life cycle of a servlet and configuring a servlet in the web.xml file. In addition, you learn
to create a sample servlet in two ways, by mapping it in the web.xml file and by using annotations.
Moreover, the unit also provides a walkthrough to the noteworthy interfaces of the javax.servlet and
javax.servlet.http packages. Toward the end of the unit, you learn about Java Server Pages(JSP).
Learning Objectives
Learning Outcomes
ftp://www.redbooks.ibm.com/redbooks/magellan/sg245755.PDF
14.1 INTRODUCTION
A servlet is a simple Java class, which is dynamically loaded on a Web server and thereby enhances the
functionality of the Web server. Servlets are secure and portable as they run on the Java Virtual Machine
(JVM) embedded with the Web server and cannot operate outside the domain of the Web server. In other
words, servlets are objects that generate dynamic content after processing requests that originate
from a Web browser. They are Java components that are used to create dynamic Web applications.
Servlets can run on any Java-enabled platform and are usually designed to process HyperText Transfer
Protocol (HTTP) requests, such as GET and POST. Besides servlet, the JSP technology can also be used to
create web pages. It has gained popularity over servlet because it is easier to maintain due to separation
between designing and development of Web pages.
JSP stands for Java Server Pages, which is a Java-based technology developed to simplify the
development of dynamic Web pages. JSP pages provide a means of separating the presentation logic
from the business logic and help to directly embed Java code in static Hyper Text Markup Language
(HTML) pages. The presentation logic is provided by HTML tags and the business logic for dynamic
content is handled by JSP tags. JSP is a server-side technology and JSP pages are processed on a Web
server in the JSP Servlet engine. When a client requests for a JSP page, the JSP Servlet engine first
processes the requested page to generate the HTML code for dynamic content, then compiles the page
into a servlet, and then executes the resulting servlet to generate an output to the client.
14.2 SERVLETS
The Java Servlet technology provides a simple, vendor-independent mechanism to extend the
functionality of a Web server. This technology provides high level, component-based, platform-
independent and server-independent standards to develop Web applications in Java. The Java Servlet
technology is similar to other scripting languages, such as Common Gateway Interface (CGI) scripts,
JavaScript (on the client-side) and Hypertext Preprocessor (PHP). However, servlets are more acceptable
since they overcome the limitations of CGI, such as low performance and scalability. Now, Let us learn
Java Servlet key features in detail:
Request and Response Model: Servlets are based on the programming model that accepts requests
and generates responses accordingly. A developer extends the GenericServlet or HttpServlet class
2
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
to create a servlet. The service() method in a servlet is defined to handle requests and responses. The
following code snippet defines the service() method for the MyServletApplication servlet class:
import javax.servlet.*;
public class MyServletApplication extends GenericServlet {
public void service (ServletRequest request, ServletResponse
response) throws ServletException, IOException
{
...
}
...
}
The service() method is provided with request and response parameters. These parameters
encapsulate the data sent by a client, which provides access to the parameters and allows servlets
to generate responses. Servlets normally use an input stream to retrieve most of their parameters,
and an output stream is used to send responses. The following code snippet shows how the request
parameter is used to invoke the getInputStream() method:
ServletInputStream input = request.getInputStream();
ServletOutputStream output = response.getOutputStream();
In the preceding code snippet, instances of the input and output streams are created, which may
be used to read or write data. Servlet and Environment StateServlets are similar to any other Java
objects and have instance-specific data. This implies that servlets are also independent applications
that run within the server environment and do not require any additional classes (which are
required by some alternative server extension APIs).
When servlets are initialised, they have access to some servlet-specific configuration data. This
enables the initialisation of different instances of the same servlet-class with different data, and
their management as differently named servlets. The data, provided with each servlet instance at
the time of its initialisation, also includes some information about the persistent state of an instance.
The ServletContext object provides the ability to servlets to interact with other servlets in a Web
application.
Usage Modes: Servlets can be used in various modes. However, these modes are not supported by all
server environments. At the core of a request–response protocol, the basic modes in which servlets
can be used are as follows:
Servlets can be chained together into filter chains by the servers
Servlets can support protocols, such as HTTP
Servlets serve as a complete, efficient and portable replacement for CGI-based extensions in
HTTP-based applications
Servlets can be used with HTML to dynamically generate some parts of a Web document in
HTTP-based applications
Servlet Life Cycle: When a server loads a servlet, the init() method of the servlet is executed. The
servlet initialisation process is completed before any client request is addressed or before the servlet
is destroyed. The server calls the init() method once, when the server loads the servlet and does not
call the method again unless the server reloads the servlet. A server cannot reload a servlet after the
servlet is destroyed. After initialisation, the servlet handles client requests and generates responses.
Finally, the destroy() method is invoked, to destroy the servlet.
3
JGI JAINDEEMED-TO-BE UNIVERSIT Y
Java Programming
Possible Sources of Servlets: When a client requests for a servlet, the server maps the request of the
client and loads the servlet. The server administrator can specify the mapping of client requests to
servlets in the following ways:
Mapping client requests to a particular servlet, for example, client requests made to a specific
database.
Mapping client requests to the servlets found in an administered servlets directory. This servlet
directory may be shared among different servers that share the processing load for the clients
of a website.
Configuring some servers to automatically invoke servlets that filter the output of other servlets.
For example, a particular type of output generated by a servlet may invoke other servlets to
carry out post processing, probably to perform format conversions.
Invoking the specific servlets without administrative intervention by properly authorised clients.
Figure 1 displays the various sources of servlets:
Java Server
Pull
Remote Server
Servlet2 Servlet3 Servlet4
Pull Trusted Client
Push
Trusted Client
Servlet1
Servlet3 Local File
(Individually Administered
Location)
4
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
be concurrent. This enables servlets to coordinate activities among multiple clients. To share
data between requests, the class-static state may be used.
destroy(): Terminates an executing servlet. Servlets process client requests until they are
explicitly terminated by the Web server by calling the destroy() method. When a servlet is
destroyed, it becomes eligible for garbage collection.
Security Features: Servlets have access to information about their clients. Peer identities can be
determined reliably when servlets are used with secure protocols, such as Secure Sockets Layer
(SSL). Servlets that rely on HTTP also have access to HTTP-specific authentication data. Servlets
have various advantages of Java. For example, as in Java, memory access violations and strong
typing violations are also not possible with servlets. Due to these advantages, faulty servlets do
not crash servers, which is common in most C language server extension environments. Java
Servlet provides strong security policy support unlike any other current server extension API.
This is because a security manager, provided by all Java environments, can be used to control the
permissions for actions such as accessing a network or file. Servlets are not considered trustworthy
in general and are not allowed to carry out the actions by default. However, servlets that are
either built into the server, or digitally signed servlets that are put into Java ARchive (JAR) files
are considered trustworthy and granted permissions by the security manager. A digital signature
on any executable code ensures that the organisation that created and signed the code takes the
guarantee of its trustworthiness. Such digital signatures cannot support answerability for the code
by themselves. However, they do provide assurance about the use of that code. For example, all code
that accesses network services within a corporate Intranet of the Management Information System
(MIS) organisation may require having a particular signature, to access those network services. The
signature on the code ensures that the code does not violate any security policy. Figure 2 displays the
approaches to server extensions depicting the Java server security manager layer used by servlets
to verify permissions:
NativeCode
Libraries Java Server Security Manager
5
JGI JAINDEEMED-TO-BE UNIVERSIT Y
Java Programming
In languages such as C or scripting languages, the extension APIs cannot support fine-grained
access controls, even if they do allow digital signatures for their code. This explains that Pure
JavaTM extensions are fundamentally more secure than current competitive solutions including, in
particular ActiveX of Microsoft.
There are some immediate commercial applications for such improved security technologies. At
present, it is not possible for most Internet Service Providers (ISPs) to accept server extensions from
their clients. The reason is that the ISPs do not have the proper methods to protect themselves or
their clients from the attacks building extensions, which use native C code or CGI facilities. However,
it has been observed that extensions built with pure Java Servlet can prevent modification of data.
Along with the use of digitally signed code, ISPs can ensure that they safely extend their Web servers
with the servlets provided by their customers.
HTML-Aware Servlets: It has been observed that many servlets directly generate HTML formatted
text, because it is easy to do so with standard internationalised Java formatted output classes, such
as java.io.PrintWriter. To dynamically modify HTML pages or generate HTML pages, you do not have
to use scripting languages. You can also use other approaches to generate Java HTML formatted text.
For example, some multi-language sites that serve pages in multiple languages, such as English and
Japanese, usually maintain language-specific libraries of localised HTML template files. These sites
also display the localised HTML templates by using localised message catalogues. Other sites may
also have developed HTML generation packages. These packages are particularly well accustomed
to other specific needs for dynamic Web page generation, for example, the ones that are closely
integrated with other application toolsets. Servlets may also be invoked by Web servers that provide
complete servlet support, to help in preprocessing Web pages by using the server-side includes
functionality. This kind of preprocessing can be indicated to Web servers by a special HTML syntax.
The following code snippet shows the syntax that is used in HTML files to indicate preprocessing of
Web pages:
<SERVLET NAME=ServletClassName>
<PARAM NAME=param1 VALUE=val1>
<PARAM NAME=param2 VALUE=val2>
If you see this text, it means that the Web server providing this
page does not support the SERVLET tag. Ask your Internet Service
Provider to upgrade!
< /SERVLET>
In the preceding code snippet, the invocation style usage of the SERVLET tag indicates that a
preconfigured servlet should be loaded and initialised in cases where it has not already been done,
and then invoked with a specific set of parameters. The output of that servlet is included directly
in the HTML-formatted response. Apart from using the SERVLET tag, another invocation style can
also be used, which allows the passing of the initialisation arguments to the servlet and specifies its
CLASS and CODEBASE values directly.
The SERVLET tag could be used to insert formatted data. The formatted data can be the output of a
Web or database search, user-targeted advertising, or the individual views of an online magazine.
HTML-aware servlets can generate arbitrary dynamic Web pages in which typical servlets accept
input parameters from different sources. Some of these sources are as follows:
The input stream of a request, perhaps from an applet
The Uniform Resource Identifier (URI) of the request
Any other servlet or the network service
Parameters passed from an HTML form
6
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
The input parameters are used to generate HTML-formatted responses. A servlet often checks with
one or more databases, or other data with which the servlet is configured, to decide the exact data
that is to be returned with the response.
HTTP-Specific Servlets: HTTP-specific servlets are those servlets that are used by the HTTP
protocol. These servlets can support any HTTP method, such as GET, POST and HEAD; redirect
requests to other locations; and send HTTP-specific error messages. They can also have access to the
parameters passed through standard HTML forms. HTTP-specific servlets include the HTTP method
to be executed and the Uniform Resource Identifier (URI), which describes the destination of the
request. The following code snippet shows some of the methods used in HTTP-specific servlets:
String method = request.getMethod(); // e.g. POST
String uri = request.getRequestURI();
String name = request.getParameter("name");
String phone = request.getParameter ("phone");
String card = request.getParameter ("creditcard");
In HTTP-specific servlets, request and response data is always provided in the Multipurpose Internet
Mail Extensions (MIME) format. This implies that the servlet first specifies the data type and then
writes the encoded data. This allows servlets to refer the data format regarding arbitrary sources
of input data, and then return the data in the appropriate form for the particular request. Examples
of request and response data formats are HTML, graphics formats, such as Joint Photographic
Experts Group (JPEG) or Moving Picture Experts Group (MPEG), and data formats that are used by
some applications.
In most applications, HTTP servlets are considered better than CGI programs in terms of performance,
flexibility, portability and security. Therefore, rather than using CGI or a C language plug-in, write
your next server extension by using the Java Servlet API.
14.2.1 History
The history of development of servlet is shown in Table 1:
Year Events
1995 James Gosling originally proposed the idea of Servlets.
Early 1996 Pavani Diwanji picked the concept of servlets.
He wanted to include it in a pure Java HTTP server which was being developed by Sun
with the code name Jeeves. At that time, server-side Java did not exist.
May 1996 Sun Microsystems announced about the development of server-side equivalent to the
Java applet, that is, the Java Servlet. The Servlet API made its debut at JavaOne.
July 1996 Sun released the first alpha of Jeeves, later named Java Web Server, with the new Servlet
API.
August 1996 Sun published the first white paper, and possibly the first formal documentation of the
Servlet technology with the release of Jeeves Alpha 1.2.
December 1996 The first release of a servlet specification has taken place in this year.
June 1997 James Duncan Davidson has developed the new reference implementation of the Servlet
API with the maiden release of the Java Web Servlet Development Kit (JWSDK) and the
Java Servlet API 2.1.
7
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
Year Events
1999 Davidson, who founded the Apache Ant project, persuaded Sun Microsystems for
donating the JWSDK, the official reference implementation of the Servlet API, to the
Apache Software Foundation under a subproject called Tomcat.
2005 Apache Tomcat became a top-level Apache project
At present, Tomcat is the dominant implementation of the Servlet API and its offspring
(JSP, EL, JSPTL).
Without the Servlet API, Java might never have become a leading platform for server-side development.
8
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
We have discussed the three events or phases that form the life cycle of a servlet. However, there are many
more methods that need to be considered by a Web developer. HTTP is primarily used to access content
on the Internet. Though a basic servlet does not know anything about HTTP, a special implementation of
the servlet, namely javax.servlet.http.HttpServlet has been specifically designed for this purpose.
When the Servlet container creates a servlet for the first time, the container invokes the init() method
of the servlet. After this, each user request results in the creation of a thread, which calls the service()
method of the respective instance. Though the servlet in question can implement a special interface,
(SingleThreadModel), which stipulates that not only a single thread is permitted to run at a time, but
also multiple concurrent requests can be made. The service() method then calls the doGet(), doPost(),
or any other doXXX() method. However, the calling of the doXXX() method depends on the type of HTTP
request received. Finally, when the server decides to unload a servlet, it first calls the servlet’s destroy()
method.
Let’s now discuss the various methods used in the life cycle of the servlet.
9
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
Note:
If a servlet needs to handle both GET and POST identically, the doPost() method should call the doGet() method
or vice versa. Remember, you should not override the service()method directly.
During the entire request and response process, most of the time, you only care about the GET or POST
requests. Therefore, you override either the doGet() method or the doPost()method or both. However, if
required, you can also override the following methods depending upon the request types:
The doDelete() method for DELETE requests
The doPut() method for PUT requests
10
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Remember, however, that you have automatic support for OPTIONS and TRACE.
The doHead() method is not provided in versions 2.1 and 2.2 of the Servlet API, because in those versions
the system answers HEAD requests automatically by using the status line and header settings of the
doGet() method. However, the doHead() method is included in version 2.3 to enable the generation of
responses to HEAD requests.
Note:
It is not recommended to implement the finalise() method in the servlet object; instead, provide the code for the
finalisation tasks of an application in the destroy() method.
src
Webapps myApps
WEB-INF classes
11
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
3. Write the servlet program and save the JAVA file in the src folder, created in the myApps folder
under %CATALINA_HOME%\webapps folder. For example, we have created FirstServlet.java file as
shown in Program 1:
Program 1: Showing the Code for the FirstServlet.java File
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http:// xmlns.jcp/org/xml/ns/javaee
http:// xmlns.jcp/org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
12
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FServlet</url-pattern>
</servlet-mapping>
</web-app>
6. Start the Tomcat server by using the “startup” command.
7. Call the servlet from a Web browser. By default, Tomcat runs on port 8080 in myApps virtual directory
under the servlet subdirectory. The servlet that you just wrote is named FirstServlet. The URL for
that servlet has the following format:
http://domain-name/virtual-directory/servlet/servlet-name
If you run the web browser from the same computer as Tomcat, you can replace domain-name with
localhost. Therefore, the URL for your servlet would be http://localhost:8080/myApps/FServlet, as
shown in Figure 4:
Note:
After executing the application, stop the Tomcat server by using the “shutdown” command.
13
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
The central abstraction of the Servlet API is the Servlet interface. The two classes in the Servlet API that
implement the Servlet interface are GenericServlet and HttpServlet. Generally, developers implement
the HttpServlet interface to create their servlets for Web applications that employ the HTTP protocol.
The basic Servlet interface defines a service() method to handle client requests,. This method is called for
each request that is routed to an instance of a servlet by the Servlet container.
The contract between a Web application and a Web container is provided by the javax.servlet package.
This allows Servlet container vendors to focus on developing the container in the manner most suited
to their requirements (or those of their customers), as long as the package provides the specified
implementations of the interfaces used in a servlet. The package provides a standard library to process
client requests and develop servlet-based applications, from a developer’s perspective.
The Servlet interface that defines the core structure of a servlet is provided in the javax.servlet package,
which is the basis for all servlet implementations. However, for most servlet implementations, the
subclass from a defined implementation of this interface provides the basis for a Web application.
The various interfaces and classes, such as ServletConfig and ServletContext, provide the additional
services to a developer. An example of such a service is the Servlet container that provides a servlet with
access to a client request through a standard interface. The javax.servlet package, therefore, provides
the basis to develop a cross-platform, cross-servlet container Web application, and allows programmers
to focus on developing a Web application.
Developers sometimes also use the javax.servlet.http package. Additionally, you need the javax.servlet
package to build servlet implementations that use a non-HTTP protocol. For example, you can extend
classes from the javax.servlet package to implement a Simple Mail Transfer Protocol (SMTP) servlet
that provides an e-mail service to clients.
The javax.servlet package comprises fourteen interfaces. While building an application, a programmer
can implement seven interfaces, such as Servlet, and ServletRequestListener. A Servlet container
provides the implementation of the following seven interfaces:
ServletConfig
ServletContext
ServletRequest
ServletResponse
RequestDispatcher
FilterChain
FilterConfig
The Servlet container must provide an object for the preceding interfaces to a servlet. The
getServletContext() method is probably the most important method of the ServletConfig Interface.
This method returns the ServletContext object, which communicates with the Servlet container when
you want to perform some action, such as writing to a log file or dispatching requests. There is only
one ServletContext object for a Web application per JVM. This object is initialised when the Web
application starts and is destroyed only when the Web application shuts down. One useful application
of the ServletContext object is as a persistence mechanism. A programmer may store attributes in the
ServletContext interface so that they are available throughout the execution of an application and not
just for the duration of a request for a resource.
14
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
The Servlet container provides the classes that implement the ServletRequest and ServletResponse
interfaces. These classes provide client request information to a servlet and the object used to send a
response to the client.
An object defined by the RequestDispatcher interface manages client requests by directing them to an
appropriate resource on the server.
The FilterChain, FilterConfig and Filter interfaces are used to implement the filtering functionality in
an application. You can also combine the interfaces into chains, implying that you can chain them such
that before being processed by a container, the request is filtered through each filter defined in the
application. The response goes down the chain in reverse. A programmer building a Web application
implements the following seven interfaces:
Servlet
ServletRequestListener
ServletRequestAttributeListener
ServletContextListener
ServletContextAttributeListener
SingleThreadModel
Filter
The preceding interfaces are defined so that a Servlet container can invoke the methods defined in the
interfaces. Therefore, the Servlet container needs to know only the methods defined in the interfaces.
The details of the implementation of the methods are provided by the developers.
The event classes used to notify the changes made to the ServletContext object and its attributes are
ServetContextEvent and ServletContextAttributeEvent, respectively.
Initially, the system creates a single instance of a servlet. If a new request is received while the previous
one is being processed, a new thread is created for each new user request, with multiple threads
running concurrently. This implies that the doGet() and doPost() methods need to carefully synchronise
the access to fields and other shared data because, multiple executing threads may access the data
simultaneously. You can implement the SingleThreadModel interface in a servlet, if you want to prevent
this multithreaded access, as shown in the following code snippet:
public class YourServlet extends HttpServlet implements SingleThreadModel
{
...
}
If you implement the SingleThreadModel interface, the system ensures that a single instance of a servlet
is never accessed by more than one request thread. This is implemented by queuing all the requests and
passing them one by one to a single servlet instance. However, the server can create a pool of multiple
instances, with each addressing one request at a time. This implies that there is no need to worry about
simultaneous access to regular fields (instance variables) of a servlet. However, access to class variables
(static fields) or shared data stored outside the servlet still needs to be synchronised.
Synchronous and frequent access to servlets can significantly hurt performance (latency). The server
remains idle instead of handling pending requests, when a servlet waits for Input/Output (I/O). Therefore,
think twice before using the SingleThreadModel approach.
Note: The SingleThreadModel interface has been deprecated as of Java Servlet API 2.4, with no direct replacement
15
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
Two classes, ServletRequestEvent and ServletRequestAttributeEvent, are used to indicate the life cycle
events and attribute events for a ServletRequest object. The ServletContext object of a Web application
is the source of the event.
To read or send binary data to or from a client, the ServletInputStream and ServletOutputStream classes
provide input and output streams, respectively.
Useful implementations of the ServletRequest and ServletResponse interfaces are provided by
the wrapper classes ServletRequestWrapper and ServletResponseWrapper, respectively. These
implementations can be subclassed to allow programmers to adapt or enhance the functionality of the
wrapped object for their own Web application. This can be done to implement a basic protocol agreed
between a client and a server or to transparently adapt the requests or responses to a particular format
that the Web application requires.
The following two exceptions are present in the javax.servlet package:
ServletException
UnavailableException
Generally, the ServletException exception is thrown by a servlet to indicate a problem with a user
request. The problem may be in processing a request or sending of a response.
Whenever the ServletException exception is thrown into a Servlet container, an application loses
control of the request being processed. It is the responsibility of the Servlet container to clean up the
request and return a response to a client. Instead of sending a response, the Servlet container may also
return an error page to the client indicating a server problem, depending on the implementation and
configuration of the container.
A ServletException exception should be thrown only as a last resort. The preferred approach to deal with
an insuperable problem is to handle the problem and then return the type of the problem to the client.
An application throws the UnavailableException exception when a requested resource is not available.
The resource can be a servlet, a filter, or any other configuration details required by the servlet to
process requests, such as a database, a domain name server, or another servlet.
16
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
HttpSessionActivationListener
HttpSessionAttributeListener
HttpSessionListener
The HttpServletRequest interface retrieves data from a client to a servlet for use in the HttpServlet.
service() method. This interface allows the service() method to access the HTTP protocol specified header
information. The HttpServletResponse interface allows the service() method of a servlet to manipulate
the HTTP protocol specified header information. This interface also returns the data to its client. The
HttpSession interface is used to maintain a session between an HTTP client and the HTTP server. This
session is used to maintain the state and user identity across multiple connections or requests during a
given period.
The HttpSessionContext interface provides a group of the HttpSessions objects associated with a single
session. The getSessionContext() method is used by a servlet to get the HttpSessionContext object. The
HttpSessionContext interface also provides various methods to servlets to list the IDs or retrieve a
session based on the ID. The HttpSessionActivationListener interface notifies a Web container about
the activation or passivation of a session object. The HttpSessionAttribute interface is implemented
to receive the notifications of changes in the attribute lists of sessions within a Web application. The
HttpSessionListener interface notifies the changes made in the active sessions in a Web application.
Note: The HttpSessionContext interface has been deprecated as of JavaTM Servlet API 2.1 for security reasons,
with no replacement.
The HttpSessionBindingListener interface has the valueBound() and valueUnbound() methods to notify
a listener that it is being bound to a session or unbound from a session. Apart from the interfaces, the
javax.servlet.http package also has various classes, which are as follows:
Cookie
HttpServlet
HttpServletRequestWrapper
HttpServletResponseWrapper
HttpSessionBindingEvent
HttpSessionEvent
HttpUtils
HttpServlet is an abstract class that simplifies the writing of HTTP servlets. As HttpServlet is an abstract
class, servlet programmers must override at least one of the following methods: doGet(), doPost(),
doPut(), doDelete() and getServletInfo(). The HttpServletRequestWrapper class provides a convenient
implementation of the HttpServletRequest interface to adapt a request to a servlet. Similarly, the
HttpServletResponseWrapper class provides a convenient implementation of the HttpServletResponse
interface to adapt the response from a servlet. The HttpSessionBindingEvent class communicates to
the HttpSessionBindingListener object regarding bounding to or unbounding from the HttpSession
value. The HttpSessionEvent class represents event notifications for changes in a session within a Web
application. As already discussed, the HttpSession interface maintains a session and manages the
session with the help of the Cookie class. The HttpUtils class is a collection of static utility methods useful
to HTTP servlets.
17
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
18
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
used in the same way when data is sent by the GET request as when it is sent by the POST request.
The servlet can identify which request method is used and automatically returns the String
value according to the URL-decoded value of the first occurrence of that parameter name. If the
parameter exists but has no value, an empty String is returned. In addition, if no such parameter
exists, null is returned. You should call the getParameterValues () method (which returns an array
of Strings) instead of the getParameters()method (which returns a single String), if the parameter
can potentially have more than one value. The return value of the getParameterValues () method is
null for parameter names that do not exist. A single element array is returned when only a single
value exists for the parameter.
Parameter names are case-sensitive; therefore, for example, request.getParameter(“Param1”) and
request.getParameter(“param1”) are not interchangeable.
Finally, for debugging, it is sometimes useful to get a full list of parameters, although most real
servlets look for a specific set of parameter names. You can use the getParameterNames() method
to get the list of parameter names in the form of an enumeration, each entry of which can be cast
to a String and used in the getParameter() or getParameterValues() method . You should note that
the order in which the parameter names appear within the enumeration is not specified by the
HttpServletRequest interface.
Let us now discuss the role of request parameters. Perhaps the most commonly used methods of
the HttpServletRequest object are getParameter() and getParameters()that involve getting request
parameters. Whenever an HTML form is filled and sent to a server, the fields of the form are passed
as parameters. This includes any information sent through input fields, selection lists, combo
boxes, check boxes and hidden form fields. However, the form submission excludes file uploads. Any
information passed as a query string is also available on the server-side as a request parameter. The
HttpServletRequest object includes the following methods to access request parameters:
getParameter(java.lang.String parameterName): Takes a parameter name as a parameter
and returns a String object representing the corresponding value. This method returns null
when it does not find a parameter of the given name.
getParameters(java.lang.String parameterName): Allows you to get all the parameter values
for the same parameter name returned as an array of Strings. The getParameters() method is
similar to the getParameter() method. However, note that the getParameters() method should
be used when there are multiple parameters with the same name. Often, an HTML form check
box or combo box sends multiple values for the same parameter name.
getParameterNames(): Returns the parameter names in the form of an enumeration, which
are used in a request. This method can be used with the getParameter() and getParameters()
methods, to obtain a list of names and values of all the parameters included with a request.
Let’s now create a servlet that reads and displays all the parameters sent with a request. You can use
such a servlet to get a little more familiar with parameters, and to debug HTML forms by seeing the
information being sent. Program 2 provides the code for such a servlet (save the ShowParameters.
java file in the src folder):
Program 2: Displaying the Code for the ShowParameters.java File
import java.util.*;
import java.io.*;
import javax.servlet.*;
19
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
import javax.servlet.http.*;
while (enm.hasMoreElements())
{
String pName = (String) enm.nextElement();
String[] pValues = request.getParameterValues(pName);
out.print("<b>"+pName + "</b>: ");
for (int i=0;i<pValues.length;i++)
{
out.print(pValues[i]);
}
out.print("<br>");
}
out.println("</body>");
out.println("</html>");
}
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException
{
doGet(request, response);
}
}
Save the ShowParameters.java file in the src and compile and run the ShowParameters servlet in the
FirstApp Web application with a mapping to the /ShowParameters path. Now, create a few simple
HTML forms and use the servlet to see the parameters being sent. In Program 3, ShowParameters.
html provides a sample HTML form (save the ShowParameters.html file in the \FirstApp folder):
Program 3: Showing the Code for the ShowParameters.html File
<html>
<head>
<title>Example HTML Form</title>
20
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
</head>
<body>
<p>To debug a HTML form set its 'action' attribute to reference the
ShowParameters Servlet.</p>
<form action="ShowParameters" method="post">
Name: <input type="text" name="name"><br>
Password: <input type="password" name="password"><br>
Select Box:
<select name="selectbox">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select><br>
Importance:
<input type="radio" name="importance" value="very">Very,
<input type="radio" name="importance" value="normal">Normal,
<input type="radio" name="importance" value="not">Not<br>
Comment: <br>
<textarea name="textarea" cols="40" rows="5"></textarea><br>
<input value="Submit" type="submit">
</form>
</body>
</html>
Save the ShowParameters.html file in the base directory of the FirstApp Web application and deploy
the new WAR file. After deploying the file, browse the following URL:
http://localhost:8080/myApps/ShowParameters.html
The ShowParameters.html page is displayed, as shown in Figure 5:
21
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
After entering the relevant details in the HTML form (Figure 5), the parameters are sent to the
ShowParameters servlet. The parameters sent from the ShowParameters.html page are displayed
by the ShowParameters Servlet, as shown in Figure 6:
22
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
getHeader(java.lang.String name): Returns the specified request header value as a String. This
method returns null if the request does not include a header of the specified name. The header
name is case insensitive. A user can use this method with any request header.
getHeaders(java.lang.String name): Returns all the specified request header values as an
enumeration of String objects. Sometimes, a client can send the header values as an enumeration
of String objects, rather than sending the header as a comma-separated list. Each of these
headers can have a different value. If the request includes no header of the specified name,
this method returns an empty Enumeration object. The header name is case insensitive in this
method also as well. The user can use this method with any request header.
getHeaderNames(): Returns an enumeration of the names of all the headers sent by a request.
In combination with the getHeader() and getHeaders() methods, the getHeaderNames() method
can be used to retrieve the names and values of all the headers sent with a request. Some
containers do not allow access to HTTP headers. In that case, null is returned.
getIntHeader(java.lang.String name): Returns the value of the specified request header as
an int type. A value of -1 is returned by this method if the request does not contain a header
of the specified name. A NumberFormatException exception is thrown if the header cannot be
converted to an integer.
getDateHeader(java.lang.String name): Returns the specified request header value as a long
value representing a Date object. The returned date is counted as the number of milliseconds
since the epoch. The header name is case insensitive. A value of -1 is returned if a request header
of the specified name is not found. An IllegalArgumentException exception is thrown if the
header cannot be converted to a date.
File Uploads: File uploads are simple for HTML developers, but difficult for server-side developers.
Usually, discussions on Servlets and HTML forms conveniently skip the topic of file uploads.
However, a servlet developer must have a good understanding of HTML form file uploads. For
example, consider a situation where a client needs to upload something besides a simple string
of text, such as a picture. In this case, using the getParameter() method will not work because it
produces unpredictable results. Therefore, to read the picture uploaded the Servlet API provides
the MIME type. There are two primary MIME types for form information, application/x-www-form-
urlencoded and multipart/form-data. In the MIME type application/x-www-form-urlencoded, the
results in the Servlet API automatically parse out name and value pairs. The information is then
available by invoking HttpServletRequest.getParameter() or any of the other related methods
as described earlier. The second MIME type, multipart/form-data, is usually considered difficult,
because the Servlet API does not provide any support for it. The information is left as it is and you
are responsible for parsing the request body by using either the getInputStream() or getReader()
method. After discussing the implementation of the HttpServletRequest interface, let’s learn about
the HttpServletResponse interface.
23
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
method to write the content. A suitable object is returned by these two methods to send either text or
binary content to a client. Only one of the two methods can be used with a given HttpServletResponse
object. An exception is thrown if you try calling both the methods. The HttpServletResponse object is
also used to provide an PrintWriter instance to print the response on a browser. The following code
snippet displays the welcome message on the browser:
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Welcome Message</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>Welcome to the Users</p>");
In the preceding code snippet, the getWriter() method is used to get an output stream to send the HTML
markup. When you use an instance of the PrintWriter object, you need to provide a String object and call
the print(), println(), or write() method.
In this section, you learn about the implementation of the HttpServletResponse interface under the
following headings:
Response header
Response redirection
Response redirection translation issues
Auto-refresh/wait pages
Response Header
The HttpServletResponse object is used to manipulate the HTTP headers of a response and to send the
content back to a client. HTTP response headers inform a client the type and amount of content being
sent, and the type of server sending the content.
The HttpServletResponse object includes the following methods to manipulate HTTP response headers:
addHeader(java.lang.String name, java.lang.String value): Adds a response header having the
given name and value. This method can be used to create response headers with multiple values.
containsHeader(java.lang.String name): Returns a Boolean value that indicates whether the
named response header is already been set or not.
setHeader(java.lang.String name, java.lang.String value): Sets the name and value of a response
header as specified in the arguments. The previous value is overwritten, if the header is already set.
The containsHeader() method can be used to test whether a header is already present or not, before
setting its value.
setIntHeader(java.lang.String name, int value): Sets the name and integer values for a response
header, as specified in the arguments. The previous value is overwritten, if the header is already set.
The containsHeader() method can be used to test whether a header is already present or not, before
setting its value.
setDateHeader(java.lang.String name, long date): Sets the given name and date values for a
response header. The date is provided in terms of milliseconds since the epoch. The previous value is
overwritten with the new value, if the header is already set.
24
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
addIntHeader(java.lang.String name, int value): Adds a response header having the name and
integer values, as specified in the arguments. Response headers can be assigned multiple values
when created by using this method.
addDateHeader(java.lang.String name, long date): Adds a response header having the name and
date values, as specified in the arguments. The previous response header values are not overwritten
and response headers can have multiple values.
Table 2 provides a description of the HTTP response header fields and their values:
25
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
As the container handles the process of sending a cookie, the servlet code is not required while using
cookies. A Web browser automatically handles the process of sending cookies back to the server unless
the user disables cookies.
The cookie is used by the container to maintain a session. Cookies can be retrieved by a servlet by using
the getCookies() method of the HttpServletRequest object. The cookie attributes can be examined by the
servlet using the accessor methods of the javax.servlet.http.Cookie objects.
The servlet container sends a cookie to the client. Upon each HTTP request, the cookie is returned back
to the server. This way, the session id indicated by the cookie is associated with the request. You should
note that you can use HTTP cookies to store information about a session and for each subsequent
connection the current session can be looked up and then information about that session is extracted
from a location on the server machine. For example, in the following code snippet, the code to retrieve
the session information is provided that can be implemented in a servlet:
String sesID = makeUniqueString();
Hashtable sesInfo = new Hashtable();
Hashtable hashtab = findTableStoringSessions();
hashtab.put(sesID, sesInfo);
Cookie sesCookie = new Cookie("JSESSIONID", sesID);
sesCookie.setPath("/");
response.addCookie(sesCookie);
The preceding code snippet requests the server, which uses the hashtab hash table to associate a session
ID of the JSESSIONID cookie with the sesInfo hash table of data associated with that particular session. A
cookie is the most widely used approach for session handling. The servlet’s session tracking API handles
sessions and performs the following tasks:
Extracting the cookie that stores other cookie’s session identifier
Setting an appropriate expiration time for the cookie
Associating hash tables with each request
Generating a unique session identifier
Now, let’s discuss the Cookies API as it would help you to understand about the classes and interfaces
used for session tracking.
In Java Servlet API, Cookie is a class of the javax.servlet.http package, which abstracts the notion
of a cookie. You can implement session tracking using cookies with the help of the addCookie() and
getCookies() methods. These methods are provided by the javax.servlet.http.HttpServletRequest and
javax.servlet.http.HttpServletResponse interfaces and are used to add cookies to HTTP responses and
to retrieve the cookies from HTTP requests, respectively. A cookie is abstracted by the Cookie class. The
following code snippet shows a constructor that instantiates a cookie instance with the given name and
value:
public Cookie(String name, String value)
The Cookie class provides various methods, such as getValue() and setValue(),which simplify working
with cookies. For all the cookie parameters, the Cookie class provides getter and setter methods. The
following code snippet shows the implementation of some of the methods of the Cookie class:
public String getValue()
public void setValue(String newvalue)
26
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
The getter and setter methods can be used to access or set the value of a cookie. Similarly, there exist
other methods that can be used to access or change other parameters, such as path and header of a
cookie. The following code snippet shows the implementation of the addCookie() method provided by the
javax.servlet.http.HttpServletResponse interface to set cookies:
public void addCookie(Cookie cookie)
To set multiple cookies, you can call this method as many times as you want. The following code
snippet shows the implementation of the getCookies() method provided by the javax.servlet.http.
HttpServletRequest interface to extract all cookies contained in the HTTP request:
public Cookie[] getCookies()
Now, you can create your servlet to track the activities of a user using cookies by providing the code for
the following actions:
Check if there is a cookie contained in the incoming request
Create a cookie and send it with the response, if there is no cookie in the incoming request
Display the value of the cookies, if there is a cookie in the incoming request
Let us create a new Web application, HandleSession, to implement session tracking using cookies. Let’s
now create the CookieServlet servlet class (in the HandleSession application) to show how to work with
a cookie. Program 4 shows the code of the CookieServlet.java file (save the CookieServlet.java file in the
src folder):
Program 4: Showing the Source Code of the CookieServlet Servlet Class
import java.io.*;
import java.util.Random;
import javax.servlet.http.*;
import javax.servlet.ServletException;
response.setContentType("text/html");
PrintWriter prnwriter = response.getWriter();
27
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
28
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.
org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>CookieServlet</servlet-name>
<servlet-class>CookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookieServlet</servlet-name>
<url-pattern>/CookieServlet</url-pattern>
</servlet-mapping>
</web-app>
Save the preceding code as the web.xml file under the WEB-INF directory of the myApps Web application.
Now, run the servlet in a browser by browsing the http://localhost:8080/myApps/CookieServlet URL.
Figure 7 displays the output of CookieServlet.java, showing the new token value for the newly created
cookie named token:
29
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
clicking the second hyperlink, the resetParam parameter is set to yes, as shown in the address bar in
Figure 8:
30
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
HTTP requests from the client. If the user visits a Web page multiple times and selects different items to
be added to the shopping cart in each visit, the stateless nature of HTTP might not relate each visit to
the same session. Therefore, even writing a stateless transaction data to persistent storage would not
be a solution in this regard.
Therefore, session tracking involves identifying the user sessions by related ID numbers and tying
the requests to their sessions by using the said ID number. Cookies and URL rewriting are the typical
mechanisms for session tracking.
The mechanism of URL rewriting is similar to that of cookies. The URL rewriting mechanism uses the
encodeURL() method of the response object to encode the session ID into the URL path of a request. The
following code snippet shows an example of URL rewriting in which the name of the path parameter is
jsessionid:
http://host:port/myapps/index.html?jsessionid=6789
The server uses the value of the rewritten URL to find the session state information, and to pass the
information to the servlet. This is similar to the functionality of cookies. Although, cookies are typically
enabled; however, to ensure session tracking using URL rewriting, the encodeURL() method is used in
the servlets. In addition, the encodeRedirectURL()method is used in servlets to redirect to a resource.
According to the Servlet specification, if cookies are enabled, then any call to the encodeURL() and
encodeRedirectURL() methods does not result in any action. In case the cookies are disabled, the servlet
can call the encodeURL() method of the response object to append a session ID to the URL path for each
request. Alternatively, the encodeRedirectURL() method is used to redirect a Web page to a resource.
As a result, URL rewriting helps in associating the request with the session. URL rewriting is the most
commonly used mechanism for session tracking in cases when clients do not accept cookies.
Although, the URL rewriting mechanism can solve the problem of session tracking, it has two main
limitations:
It is not a secure session tracking mechanism as the token or session id is visible in the URL during
a session
It can only be used with servlets or other dynamic pages as the links in static pages are hardcoded
and cannot change dynamically for every user
Note: You can use cookies as a session tracking mechanism to overcome the preceding problems of the URL
rewriting mechanism.
Creating a Session
A prospective session that has not yet been established is considered new. As HTTP protocol is request-
response based; therefore, the HTTP session is considered as new until it is joined by a client. The client
is considered to have joined the session when session tracking information is returned to the server
31
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
indicating that the session has been successfully established. Any next request from the client is not
recognised as a part of the session until the client joins the session. A session is considered to be new, in
either of the following cases:
The client does not have knowledge about the session
The client opts for not joining the session
In both the cases, the servlet container could not correlate a request with the previous request by any
means. Therefore, a servlet developer must design the application in such a manner that it could handle
a situation where a client has not yet joined a session or will not join a session.
As explained earlier, the servlet container uses the HTTP session objects that implement the javax.
servlet.http.HttpSession interface to track and manage the user sessions. The HttpSession interface
contains public methods, such as setAttribute() and getAttribute(), to set as well as get the session
information, respectively.
The following code snippet shows the implementation of the setAttribute() method of the HttpSession
interface:
void setAttribute(String name, Object value)
The setAttribute() method binds the specified object under the specified name, to the session. The
following code snippet shows the implementation of the getAttribute() method of the HttpSession
interface:
Object getAttribute(String name)
The getAttribute() method retrieves the object that is attached to the session with the specified name.
A null value is returned if there is no match. According to the configuration of a servlet as well as
the servlet container, sessions may automatically expire after the specified time or the servlet may
invalidate the session explicitly. The following methods can be used by servlets to manage the session
life-cycle specified by the HttpSession interface:
void invalidate(): Invalidates the session instantly and unbinds any bound objects from the session.
void setMaxInactiveInterval(int interval): Sets a session timeout interval as an integer value in
seconds. Timeout cannot be indicated by a negative value. A value of 0 results in immediate timeout.
boolean isNew(): Returns true if a new session is created within the request that creates a new
session; otherwise, it returns false.
long getCreationTime(): Returns the time of creation of the session object. The time is measured in
milliseconds and is calculated since midnight, January 1, 1970.
long getLastAccessedTime(): Returns the time associated with the most recent request made by
the client during the session. The time is measured in milliseconds and is calculated since midnight,
January 1, 1970. Session creation time is returned by the method if the client session has not yet been
accessed.
Let’s create a servlet to understand the implementation of the HTTP session object. Program 5 provides
the code of the MySessionServlet servlet class, which creates the HttpSession object and prints the data
held by the request and session objects (save the MySessionServlet.java file in the src folder):
Program 5: Showing the Code of the MySessionServlet.java File
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
32
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
import java.util.Date;
if (count == null)
{
count = new Integer(1);
}
else
{
count = new Integer(count.intValue() + 1);
}
prnwriter.println("<BR>");
33
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
prnwriter.println("<BR><BR>");
34
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Data</TH>");
prnwriter.println("</body>");
prnwriter.close();
35
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
}
}
Save MySessionServlet in the src directory of the myApps Web application. Now, configure and map the
MySessionServlet servlet class to the /MySessionServlet url pattern in the web.xml file.
The code of web.xml file is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.
org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>MySessionServlet</servlet-name>
<servlet-class>MySessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MySessionServlet</servlet-name>
<url-pattern>/MySessionServlet</url-pattern>
</servlet-mapping>
</web-app>
Browse the URL http://localhost:8080/myApps/ MySessionServlet to see the output of the
MySessionServlet servlet class.
Figure 10 shows the output of the MySessionServlet servlet class, displaying the results of the accessor
methods on the request and session objects as well as listing request and session data:
36
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
37
JGI JAINDEEMED-TO-BE UNIVERSIT Y
Java Programming
In the page translation stage, the Web container performs the following operations:
Locates the requested JSP page
Validates the syntactic correctness of the JSP page
Interprets the standard JSP directives, actions and custom actions used in the JSP page
Writes the source code of the equivalent servlet for the JSP page
After a JSP page is translated into a servlet, all the requests for that JSP page are served by its
corresponding servlet class. This servlet class works similar to any other simple servlet. The
translation of a JSP is done automatically by the Web server. JSP page translation occurs only when
necessary, that is, at some point before the page has to serve its first request. This process is also
performed when the JSP source code is updated and the page is redeployed. A Web container can
decide when the translation should occur. The two possible instances where a translation can occur
are as follows:
When a first-time user requests a JSP page.
When a JSP page is loaded into a Web container. This is also called JSP pre-compilation.
If there is any error in the translation of the page, the container raises the 500 (internal server error)
exception and if a change occurs in the JSP page, all the stages of the JSP life cycle are executed
again.
The Compilation Stage: The page translation stage is followed by the compilation stage of the JSP
life cycle. In the compilation stage, the Java source code for the corresponding servlet is compiled
by the JSP container. The container converts the source code into Java byte (class) code. After the
class file is generated, the container decides to either discard the code or retain it for debugging.
Generally, most containers discard the generated Java source code by default. After the compilation
stage, the servlet is ready to be loaded and initialised.
The Loading & Initialisation Stage: During the loading and the initialisation stage of the JSP life
cycle, the JSP container loads and instantiates the servlet that has been generated and compiled in
the translation and compilation stages, respectively. The JSP container, as part of the loading and
initialisation process, performs the following operations:
Loading: Loads the servlet generated during the translation and compilation stages. Normal
Java class loading options are used to load the servlet. The loading process is terminated if the
Web container fails to load the servlet class.
Instantiation: Creates an instance of a servlet class. To create a new instance of the generated
servlet, the JSP container uses the no-argument constructor. The JSP translator (part of the JSP
container) is responsible for including a no-argument constructor in the servlet generated after
the translation of the JSP page.
Initialisation: Initialises the instantiated object after successful instantiation of the JSP
equivalent servlet object. As per the servlet’s life cycle, the container initialises the object by
invoking the init (ServletConfig) method. This method is implemented by the container by calling
the jspInit() method. This indicates that the jspInit() method acts as the init(ServletConfig)
method of the servlet.
If the loading and initialisation stage is performed successfully, the Web container activates the
servlet object and makes it available and ready to handle client requests.
Note: A JSP page equivalent servlet instance, put into service in a container may not handle any request in
its lifetime.
38
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
The next stage in the JSP life cycle is the request handling stage.
The Request Handling Stage: During the request handling stage of the JSP life cycle, only those
objects of a JSP equivalent servlet that are initialised successfully are used by the Web container
to handle client requests. The container performs the following operations in the request handling
stage:
Creates the ServletRequest and ServletResponse objects. If a client uses the HTTP protocol to
make a request, the container creates the HttpServletRequest and HttpServletResponse objects,
where the request object corresponds to the client request. In other words, the request data and
client information can be retrieved by a servlet by using the request object. The response object
can be used by the servlet to generate the response to a client.
Passes the request and response objects created in the preceding step to the servlet object to
invoke the service() method. In the case of a JSP equivalent servlet, the container invokes the
_jspService() method.
The Destroying Stage: If a servlet container decides to destroy a servlet instance of a JSP page, the
container needs to end the services provided by the instance. The servlet container performs the
following operations to destroy the servlet instance:
Allows all the currently running threads in the service() method of the servlet instance to complete
their operations. Meanwhile, the servlet container makes the servlet instance unavailable for
new requests.
Allows the servlet container to invoke the destroy() method on the servlet instance, after the
current threads have completed their operations on the service() method. The destroy() method
leads to the invocation of the jspDestroy() method.
Releases all the references of the servlet instance and renders them for garbage collection,
after the destroy() method is processed. In addition, the servlet’s life cycle is complete after the
invocation of the destroy() method.
39
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
Note that if the script code is not valid, an exception is thrown at the compilation stage of the JSP life
cycle. You can include multiple scriptlet tags in a single JSP document. The following code snippet
shows the traditional JSP syntax to use a scriptlet tag:
<%
script code (allows multiple statements)
%>
The following code snippet shows the XML-based syntax for a scriptlet
tag:
<jsp:scriptlet>
script code (allows multiple statements)
</jsp:scriptlet>
Let’s now look at an example that illustrates the use the scriptlet tag. The following code snippet
shows the syntax to use a scriptlet tag in a JSP page:
<html>
<body>
<%
for (int i=0;i<5;i++)
{
out.println(i);
}
%>
</body>
</html>
In the preceding code snippet, the for loop of Java is used in a JSP page between the scriptlet tags
to print numbers 1 to 5 in five lines. The following code snippet shows the equivalent servlet code for
this JSP page, as generated by the JSP container:
public void _jspService(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
…
out.write("<html><body>");
for (int i=0;i<5;i++) {
out.print(i);
}
out.write("</body></html>");
…
The Declarative Tag: The declarative tag allows you to write the script code you need to provide in
the generated servlet class, outside the _jspService() method. This tag allows you to declare instance
and class variables and implement class methods, such as jspInit() and jspDestroy(). The following
code snippet shows the syntax of the declarative tag:
<%!
script code (allows multiple statements)
%>
The following code snippet shows the XML-based syntax for the
declarative tag:
<jsp:declaration>
script code (allows multiple statements)
</jsp:declaration>
40
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
The following code snippet shows an example illustrating the use of the declarative tag:
<%!
int a,b;
int fun(int a)
{
return a;
}
%>
<%a=1;%>
<%b=fun(a);%>
<%out.println(b);%>
In the preceding code snippet, two integer variables, a and b, and the fun() method are defined by
using the declarative tag. A value of 1 is then assigned to variable a, which is passed as an argument
to the fun() method. This method processes the argument and stores the result in variable b. Finally,
the value received by variable b is displayed on the browser.
The Expression Tag: An expression tag allows you to write a Java expression, which is then resolved
and the resultant value is displayed. The expression tag places the given Java expression in the out.
print() method during the translation stage of the JSP life cycle. Consequently, the output of the
Java expression is displayed with the output of the JSP page.
An expression tag also provides a simple and convenient way to access script (i.e., Java) variables.
The following code snippet shows the syntax of the expression tag:
<%=
script code (allows only one expression)
%>
The following code snippet shows the XML-based syntax for the
expression tag:
<jsp:expression>
script code (allows only one expression)
</jsp:expression>
Let’s now look at an example to use the expression tag. The following code snippet shows the syntax
to use an expression tag in a JSP page:
<%! int count; %>
<html>
<body>
<% count++; %>
This page is requested by <%=count%> number of users till now.
</body>
</html>
The preceding code snippet can be embedded on a JSP page to count the number of requests received
for the specific page. Each time a new user accesses the JSP page on the browser, the value of the count
variable is incremented by 1, and displayed on the browser. For example, when a user accesses the JSP
page for the first time, the count variable is declared and initialised at 0 (by default). The expression
written in the scriptlet tag (<%count++%>) increments the value of the count variable by one and prints
this value on a Web page. Now, when another user accesses this page, the value of the count variable is
incremented by 1 and the browser displays the result as 2.
41
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
Writing any code violating these rules raises a translation stage error. In addition, nested scripting
tags are not allowed in expression tags. This means that a scripting tag cannot have another type of
scripting tag. For example, consider the following code snippet:
<%
for (int i=0;i<5; i++)
{
<%=i%> //out.println(+i);
}
%>
In the preceding code snippet, the expression tag (<%= %>) is nested within the scriptlet tag (<% %>),
which would raise a translation error.
42
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
6. Type http://localhost:8080/HelloJSP.jsp in the address area of the browser and submit that address
to the browser. The output of JSP page will be displayed, as shown in Figure 11:
43
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
Click the Submit button, as shown in Figure 13. The Name is displayed on the greet.jsp page, as shown
in Figure 13:
Note: The second method is obsolete and insecure as URL can be tracked easily.
A session object can be regarded as the most commonly used implicit object implemented for storing
user data so that it can be available on other JSP pages till the user’s session is active. The session
implicit object is an instance of javax.servlet.http.HttpSession interface. This session object has various
session methods for managing data within the session scope.
The description of methods that a session object use is shown in Table 3:
Methods Description
getAttribute(String name) Allows you to get the attribute value that is set using the setAttribute()
method within this session
getAttributeNames() Allows you to get all the attributes names that are set using the
setAttribute() method
getCreationTime() Allows you to get the time of the session when it was created
getId() Allows you to get the unique id of the session
getLastAccessedTime() Allows you to get get the last accessing time of user with this session.
getMaxInactiveInterval() Allows you to get the time in seconds that specifies the maximum
time interval of user with this session that a Servlet container will be
opened for accessing
setAttribute(String name, Object value) Allows you to set the attribute value for the user within this session.
44
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Methods Description
isNew() Allows you to check whether the particular session is new or not
invalidate() Allows you to end the session
removeAttribute(String name) Allows you to remove the object attached with the specified
attribute’s name for this session
Program 8 will describe you how to use the session object in the JSP page. This program will explain you
how the session object invokes the various methods which performs an action.
Program 8: Using the Session Object in the Creatingsession.jsp Page
<%
request.getSession(true);
out.println("Is Session New : "+session.isNew());
out.println("Session Creation Time : "+session.getCreationTime
());
Object name = "Rahul";
Object title = "Kumar";
session.setAttribute("name", name);
session.setAttribute("title", title);
out.println("Name = "+ session.getAttribute("name"));
out.println("Title = "+ session.getAttribute("title"));
java.util.Enumeration e = session.getAttributeNames();
out.println("Attributes Are : ");
while(e.hasMoreElements())
{
out.println(e.nextElement());
}
session.invalidate();
%>
Now, when you run the Creatingsession.jsp page, the output appears as shown in Figure 14:
45
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
method of the request object returns an array of Cookie objects. Cookies can be constructed with the
help of the code given in Program 9:
Program 9: Cookies.jsp
<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name", request.
getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_
name"));
<html>
<head>
<title>Setting Cookies</title>
</head>
<body>
<center>
<h1>Setting Cookies</h1>
</center>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
Cookies.jsp page is invoked by the code of Program 10:
Program 10: NameCookies.html
<html>
<body>
46
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
</body>
</html>
Copy the NameCookies.html and Cookies.jsp files in the ROOT directory of Tomcat Server and start the
server. Open the NameCookies.html page on Web browser and enter the required data, as shown in
Figure 15:
A servlet is a simple Java class, which is dynamically loaded on a Web server and thereby enhances
the functionality of the Web server.
The Java Servlet technology provides a simple, vendor-independent mechanism to extend the
functionality of a Web server.
When servlets are initialised, they have access to some servlet-specific configuration data.
When a server loads a servlet, the init() method of the servlet is executed.
Servlets follow a life cycle that governs the multithreaded environment in which the servlets run.
It also provides a clear perception about some of the mechanisms available to a developer to share
server-side resources.
47
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
Servlets follow a three-phase life cycle, namely initialisation, service and destruction.
JSP is a Java-based Web application development technology and serves as an advancement of the
Java Servlet technology.
JSP greatly simplifies the process of creating dynamic Web pages.
A JSP follows a well-defined process that first involves the translation of the JSP page into its
corresponding servlet and then the compilation of the source file of the servlet into a class file.
14.5 GLOSSARY
Servlets: Refers to objects that generate dynamic content after processing requests that originate
from a Web browser.
JSP: Stands for Java Server Pages, which is a Java-based technology developed to simplify the
development of dynamic Web pages.
HTTP-specific servlets: Refers to those servlets that are used with the HTTP protocol.
HttpServletRequest interface: Retrieves data from a client to a servlet for use in the HttpServlet.
service() method
48
UNIT 14: Servlets & JSP JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
4. A cookie is used to transmit an identifier between a server and a client. The transmitting of an
identifier is in conjunction with stateful servlets, which can maintain session objects. Refer section
Servlets
5. JSP is a Java-based Web application development technology and serves as an advancement
of the Java Servlet technology. Before the introduction of JSP pages, servlets were used by Java
programmers to provide dynamic content to clients. Refer to section Java Server Pages (JSP)
https://docs.oracle.com/cd/E13222_01/wls/docs81/webapp/index.html
LAB EXERCISES
Exercise A: Write a Servlet program to Display Current Date and Time of Server on Client: Date Servlet.
Solution:
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;
public class DateServlet1 extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data
pw.println("<html><body>");
Date datetime = new Date();
pw.println("<h1>"+"Current Date & Time is: " +datetime.
toString()+"</h1>");
pw.println("</body></html>");
pw.close();//closing the stream
}
}
web.xml
49
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming
<servlet-name>DateServlet1</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Explanation: In this program, we have created a servlet named DateServlet to display the current date
of the server to the client.
Exercise B: Write a JSP Program to demonstrate Expression, Scriptlet and Directive tags.
Solution: The program, JSPLab.jsp, is as follows:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<% int a, b, c;
a = 10;
b = 20;
c = a + b;
%>
The sum of two numbers is:
<%= c %>
<br>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
Figure 18 shows the output of JSPLab.jsp:
50