16 Servlets
16 Servlets
16 Servlets
SERVLETS
Introduction
Servlet is a server-side technology written in Java. It runs inside a java enabled server or
application server. It is loaded and executed within the JVM of the Web Server or Application
Server.
Servlets more closely resemble Common Gateway Interface (CGI) scripts or programs than
applets in terms of functionality. As in CGI programs, Servlets can respond to user events from
an HTML request, and then dynamically construct an HTML response that is sent back to the
client.
Common Gateway Interface (CGI)
CGI scripts are written in C, C++ or Perl. With CGI, a server passes a client’s request to an
external program. This program executes, creates some content and sends a response to the
client. In case of an Application Server using CGI script to process a client request, the server
creates a separate instance of the CGI script to process the request. As a result, the efficiency of
the server is affected when there are a large number of concurrent requests.
Java Servlets
Using Servlets, a single process is used to handle multiple requests. This allows the main
process to share resources between multiple Servlets and multiple requests.
Web Server
Process
Request Servlet
Request Servlet
Request Servlet
Servlet Features
Besides inheriting all the Java features, Servlets have the following features.
∑ Security: A Web container provides a run time environment for executing a Servlet.
Servlets inherit the security features provided by a Web container. This allows developers to
focus on the Servlet functionality and leave the security issues to the Web container to
handle.
∑ Session management: It is the mechanism of tracking the state of a user across multiple
requests. A session maintains the client identity and state across multiple requests.
∑ Instance persistence: Servlets help to enhance the performance of the server by preventing
frequent disk access.
Web Container
A Web container provides a runtime environment for running a Servlet. It provides services
required by the Web Applications such as:
∑ Managing various stages in the life cycle of a servlet, such as initializing a Servlet instance,
processing the client request and removing the Servlet instance from service
∑ Defining the security credentials that specifies that only authorized users can use the
deployed Servlets.
∑ Managing database transactions when a Servlet needs to read and write data from a database.
∑ Creating and removing Servlet instances from an instance pool during multiple requests.
J2EE
Working of Servlets
Web
∑ Whenever a client sends a request to the Application Server for a particular Servlet, the
Application Server passes the request to the Container. The Web container checks whether
an instance of the requested Servlet exists. If the Servlet instance exists, then the Web
container delegates the request to the Servlet which processes the client request and sends
back the response.
∑ In case the Servlet does not exist, the Web container then locates and loads the Servlet class
and initializes it. Then the Servlet instance starts processing the request. The Web container
passes the response to the client.
The Java Servlet API is a set of Java classes which define a standard interface between a Web
client and a Web servlet. Client requests are made to the Web server, which then invokes the
servlet to service the request through this interface.
The API is composed of two packages:
∑ javax.servlet
∑ javax.servlet.http
IPSR Solutions Ltd www.ipsr.edu.in 3
JAVA
GenericServlet
HttpServlet
User Defined
Servlet Interface
Servlet interface
The Servlet interface is the root interface of the servlet class hierarchy. The class defines
methods which servlets must implement, including a service() method for the handling of
requests.
The main methods in javax.servlet.Servlet interface are as follows.
1. public void destroy(): the web container calls the destroy() just before removing the
servlet instance from service.
2. public ServletConfig getServletConfig(): Returns a ServletConfig object that contains
configuration information such as initialization parameters for a servlet.
3. public String getServletInfo(): Returns a string that contains information about the
servlet, such as author, version and copyright.
4. public void init(ServletConfig config) throws ServletException: The web container
calls this method after creating a servlet instance.
IPSR Solutions Ltd www.ipsr.edu.in 4
JAVA
GenericServlet Class
GenericServlet class implements the Servlet interface and defines a generic, protocol-
independent servlet. In addition to Servlet interface, it implements ServletConfig and
Serializable interfaces. The object of servletConfig interface is used by the Web container to
pass the configuration information to a servlet when a servlet is initialized.
HttpServlet Class
To develop a servlet that communicates using HTTP, we need to extend the HttpServlet class. It
extends the GenericServlet class and provides built-in HTTP functionality. HttpServlet provides
additional methods for the processing of HTTP requests such as GET ( doGet method) and
POST ( doPost method). Although our Servlets may implement a service method, in most cases
we will implement the HTTP specific request handling methods of doGet() and doPost() .
ServletConfig interface
The javax.servlet.ServletConfig is implemented by Web container to pass configuration
information to a servlet during initialization of a servlet. A servlet is initialized by passing an
object of ServletConfig to its init() by Web container. It contains initialization information and
provides access to the ServletContext object.
The object of ServletContext interface enables the servlet to communicate with the container
that hosts it.
The main methods in ServletConfig interface are:
1. public String getInitParameter(String param): Returns a string containing the value of
the specified initialization parameter or null if the parameter does not exist.
2. public Enumeration getInitParameterNames(): Returns the names of all initialization
parameters. If no parameters have been defined, an empty enumeration is returned.
3. public ServletContext getServletContext(): Returns ServletContext object for the
servlet which allows interaction with the Web container.
The ServletRequest interface contains various methods to handle client requests to access a
servlet.
IPSR Solutions Ltd www.ipsr.edu.in 8
JAVA
HTTP requests have a number of associated headers. These headers provide extra information
about the client such as name and version of browser sending the request.
Some of the important HTTP request headers are:
∑ Accept: Specifies the MIME type that the client prefers to accept
∑ Accept-Language: Specifies the language in which the client prefers to receive the
request
∑ User-Agent: Specifies the name and version of the browser sending the request.
The main methods of HttpServletRequest interface are:
1. public String getHeader(String fieldname): returns the value of the request header
field such as cache-contril and accept-language specified in parameter.
2. public Enumeration getHeaders(String name): returns all the values associated with a
specified request header as an enumeration of String objects.
3. public Enumeration getHeaderNames()
Example
The HttpSession interface contains methods to maintain the state of an end user across a Web
application. It provides support for tracking and managing the session of an end user.
The main methods are:
1. public void setAttribute(String name, Object value)
2. public Object getAttribute(String name)
3. public Enumeration getAttributeNames()
Servlet Events
The Web container provides notifications to a listener class when an event occurs during the life
cycle of the servlet. To receive notification of an event, a listener class needs to extend a listener
interface of the Servlet API.
Types of events
IPSR Solutions Ltd www.ipsr.edu.in 13
JAVA
The various events that are generated during the life cycle of a servlet are:
∑ Servlet request events
∑ Servlet context events
∑ Servlet session events
The Servlet Request Events
The events that are related to changes in the request objects associated with a Web application
are known as servlet request events.
The following two interfaces represent the servlet request events.
∑ javax.servlet.ServletRequestEvent
∑ javax.servlet.ServletRequestAttributeEvent
The Web container creates ServletRequestEvent object while:
∑ initializing a request object when a request arrives
∑ removing a request object when it is not required.
The Web container creates ServletRequestAttributeEvent object when there is a change in the
attribute of a servlet request such as:
∑ addition of an attribute to the request object
∑ removal of an attribute from the servlet request object
∑ replacement of an attribute in the servlet request object with another attribute of the same
name
The Web container creates ServletContextAttributeEvent object when there is a change in the
attribute of a servlet context such as:
∑ addition of an attribute to the context object
∑ removal of an attribute from the servlet context object
∑ replacement of an attribute in the servlet context object with another attribute of the same
name.
Example
The following program logs the time when the request and context objects are initialized and
when an attribute is added to the context object. At the same, it also logs the time when the
attribute is removed from the context object and when the request and context objects are
destroyed
Session Management
Session management is the process of keeping track of the activities of a user across Web pages.
It can also be used to keep track of the user’s preferences.
Session Management Techniques
HTTP is a stateless protocol and therefore cannot store information about the user activities
across Web pages. The techniques used to maintain the session information are:
∑ Hidden form field
∑ URL rewriting
∑ Cookies
∑ Servlet Session API
URL rewriting
This technique manages the session by modifying a URL. Usually this technique is used when
information that is to be transferred is not very critical because the URL can be intercepted
easily during transfer.
pw.println(“<a
href=\http://localhost:8080/rewrite_cntxt/servlet/SecondServlet?uname=+user+”\”>Click</a>
to proceed”>
in SecondServlet the value for uname is retrieved using request object
request. getParameter(uname);
Using Cookies
Cookies are small text files that are stored by an application server in the client browser to keep
track of all the users. A cookie has values in the form of name/value pairs.
Cookies are created by the server and are sent to the client with the HTTP response headers.
The client saves the cookies in the local hard disk and sends them along with the HTTP request
headers to the server.
A Web browser is expected to support 20 cookies per host and the size of each cookie can be a
maximum of 4 bytes. Cookies can only be read by the application server that had written them
in the client browser. Cookies can be used by the server to find out the computer name, IP
address or any other details of the client by retrieving the remote host address of the client
where the cookies are stored.
The Cookie class of javax.servlet.http package represents a cookie. The Cookie class provides a
constructor that accepts the name and value to create a cookie.
public Cookie(String,String){ }
The HttpServletResponse interface provides the addCookie() to add a cookie to the Response
object.
response.addCookie(cookiename);
The HttpServletRequest interface provides the getCookies() that returns an array of Cookies
that the request contains.
Cookie[] cookie=request.getCookies();
Methods of Cookie class
Method Description
public String getName() Returns name of the Cookie
public void setMaxAge(int expiry) Sets the maximum time for which the
client browser retains the cookie value.
public int getMaxAge() Returns the maximum age of the cookie in
seconds
Request Dispatcher
A request dispatcher is an object of the javax.servlet.RequestDispatcher interface that allows
inter-servlet communication.
The ServletContext interface provides the getRequestDispatcher(String path) method that
returns the RequestDispatcher object. With the object, we can perform the following two
functions:
∑ Include contents of another servlet
∑ Forward request to another servlet
Including contents of another servlet
dispatch.forward(request,response);
SendRedirect in servlet
The sendRedirect() method of HttpServletResponse interface can be used to redirect response to
another resource, it may be servlet, jsp or html file. It accepts relative as well as absolute URL.
It works at client side because it uses the url bar of the browser to make another request. So, it
can work inside and outside the server.
Servlet Filter
A filter is an object that is invoked at the preprocessing and postprocessing of a request. It is
mainly used to perform filtering tasks such as conversion, logging, compression, encryption and
decryption, input validation etc. The servlet filter is pluggable, i.e. its entry is defined in the
web.xml file, if we remove the entry of filter from the web.xml file, filter will be removed
automatically and we don't need to change the servlet. So maintenance cost will be less.
Usage of Filter
∑ records all incoming requests
∑ logs the IP addresses of the computers from which the requests originate
∑ conversion
∑ data compression
∑ encryption and decryption
∑ input validation etc.
Filter API
Filter has its own API. The javax.servlet package contains the three interfaces of Filter API –
Filter, FilterChain, FilterConfig
Filter Interface
For creating any filter, you must implement the Filter interface. Filter interface provides the life
cycle methods for a filter.
Method Description
public void destroy() This is invoked only once when filter is taken out of
the service.
FilterChain interface
The object of FilterChain is responsible to invoke the next filter or resource in the chain. This
object is passed in the doFilter method of Filter interface. The FilterChain interface contains
only one method:
MyFilter.java
AdminServlet.java
web.xml