You are on page 1of 25

CHAPTER 

5 Java Servlet

Servlets are modules of Java code that run in a server application hence the name "Servlets", to
answer client requests. Servlets are not tied to a specific client­server protocol but they are most
commonly  used  with  HTTP  and  the  word  "Servlet"  is  often  used  in  the  meaning  of  "HTTP
Servlet".

Servlets make use of the Java standard extension classes in the packages javax.servlet (the basic
Servlet framework) and javax.servlet.http (extensions of the Servlet framework for Servlets that
answer HTTP requests). Since Servlets are written in highly portable Java language and follow a
standard framework, they provide a means to create sophisticated server extensions in a server and
operating system independent way.

1. Introduction to Servlets

A servlet is a Java programming language class used to extend the capabilities of servers that host
applications accessed via a request­response programming model. Although servlets can respond
to any type of request, they are commonly used to extend the applications hosted by Web servers.
For such applications, Java Servlet technology defines HTTP­specific servlet classes. 

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, we 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. 

Typical uses for HTTP Servlets include:

1. Processing and/or storing data submitted by an HTML form.

2. Providing dynamic content, e.g. returning the results of a database query to the client.

3. Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system
which manages shopping carts for many concurrent customers and maps every request to the right
customer.

2. Origin of Servlets
The  rise  of  server­side  Java  applications  is  one  of  the  latest  and  most  exciting  trends  in  Java
programming. The Java language was originally intended for use in small, embedded devices. It
was  first  hyped  as  a  language  for  developing  elaborate  client­side  web  content  in  the  form  of
applets.  Until  recently,  Java's  potential  as  a  server­side  development  platform  had  been  sadly
overlooked.  Now,  Java  is  coming  into  its  own  as  a  language  ideally  suited  for  server­side
development. 

Java is inherently suited for large client/server applications. The cross­platform nature of Java is
extremely useful for organizations that have a heterogeneous collection of servers running various
flavors  of  the  Unix  and  Windows  operating  systems.  Java's  modern,  object­oriented,  memory­
protected design allows developers to cut development cycles and increase reliability. In addition,
Java's built­in support for networking and enterprise APIs provides access to legacy data, easing
the transition from older client/server systems. 

Java servlets are a key component of server­side Java development. A servlet is a small, pluggable
extension to a server that enhances the server's functionality. Servlets allow developers to extend
and customize any Java­enabled server­­a web server, a mail server, an application server, or any
custom server­­with a previously unknown degree of portability, flexibility, and ease. 

While servlets can be used to extend the functionality of any Java­enabled server, today they are
most often used to extend web servers, providing a powerful, efficient replacement for CGI scripts.
When  we  use  a  servlet  to  create  dynamic  content  for  a  web  page  or  otherwise  extend  the
functionality of a web server, we are in effect creating a web application. While a web page merely
displays static content and lets the user navigate through that content, a web application provides a
more  interactive  experience.  A  web  application  can  be  as  simple  as  a  keyword  search  on  a
document archive or as complex as an electronic storefront. Web applications are being deployed
on the Internet and on corporate intranets and extranets, where they have the potential to increase
productivity and change the way that companies, large and small, do business. 

3. Lifecycle of a Servlet

A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet

 The servlet is initialized by calling the init () method.

 The servlet calls service() method to process a client's request.

 The servlet is terminated by calling the destroy() method.

 Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in details.

The init() method :

The init method is designed to be called only once. It is called when the servlet is first created, and
not called again for each user request. So, it is used for one­time initializations, just as with the init
method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but
we can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user request
resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method
simply creates or loads some data that will be used throughout the life of the servlet.

The init method definition looks like this:

public void init() throws ServletException {
  // Initialization code...
}

The service() method :

The service() method is the main method to perform the actual task. The servlet container (i.e. web
server) calls the service() method to handle requests coming from the client( browsers) and to write
the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.)
and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method:

public void service(ServletRequest request, ServletResponse response) 
      throws ServletException, IOException{
}

The service () method is called by the container and service method invokes doGe, doPost, doPut,
doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you
override either doGet() or doPost() depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here are
the signature of these two methods.

The doGet() Method

A  GET  request  results  from  a  normal  request  for  a  URL  or  from  an  HTML  form  that  has  no
METHOD specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    // Servlet code
}

The doPost() Method

A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    // Servlet code
}

The destroy() method :

The destroy() method is called only once at the end of the life cycle of a servlet. This method gives
your servlet a chance to close database connections, halt background threads, write cookie lists or
hit counts to disk, and perform other such cleanup activities.

After  the  destroy()  method  is  called,  the  servlet  object  is  marked  for  garbage  collection.  The
destroy method definition looks like this:

  public void destroy() {
    // Finalization code...
  }

Architecture Digram:

The following figure depicts a typical servlet life­cycle scenario. 
 First the HTTP requests coming to the server are delegated to the servlet container.

 The servlet container loads the servlet before invoking the service() method.

 Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.

Figure 1. Servlet Lifecycle

4. Servlet Classes and Interfaces
This interface defines methods to initialize a servlet, to service requests, and to remove a servlet
from the server. These are known as life­cycle methods and are called in the following sequence:

a. The servlet is constructed, then initialized with the init method. 

b. Any calls from clients to the service method are handled. 

c. The servlet is taken out of service, then destroyed with the destroy method, then garbage
collected and finalized. 

In addition to the life­cycle methods, this interface provides the getServletConfig method, which
the servlet can use to get any startup information, and the getServletInfo method, which allows the
servlet to return basic information about itself, such as author, version, and copyright.
Methods of Servlet interface

1. void init(ServletConfig config)throws ServletException

Called by the servlet container to indicate to a servlet that the servlet is being placed into service.

2. ServletConfig getServletConfig()

Returns  a  ServletConfig  object,  which  contains  initialization  and  startup  parameters  for  this
servlet. The ServletConfig object returned is the one passed to the init method.

3. void  service(ServletRequest  req,  ServletResponse  res)throws  ServletException,


IOException

Called by the servlet container to allow the servlet to respond to a request.This method is only
called after the servlet's init() method has completed successfully

4. String getServletInfo()

Returns information about the servlet, such as author, version, and copyright

5. void destroy()

Called by the servlet container to indicate to a servlet that the servlet is being taken out of service.

HttpRequest Object

The HttpRequest object provides methods for extracting any or all parts of this string. In all cases,
the name parameter is case­sensitive.
 getParameter(name)—Returns  the  value  of  the  first  instance  of  the  named  parameter.
Returns nullif the parameter is not found.
 getParameterNames()—Returns a java.util.Enumeration with the names of all parameters
in the query string
 getParameterValues(name)—Returns  a  string  array  of  all  of  the  values  for  a  named
parameter
 getMethod()—Returns the HTTP method, which is either Get or Post
 getRequestURI()—Returns a string containing a URI path up to the QueryString. (Note
that the method ends with URI, not URL!)
 getQueryString()—Returns the full query string

HttpResponse Object

The HttpResponseobject has three important navigation methods.

 sendRedirect()—This method sends a new URL to the client and forces the client to the
new page. The sendRedirect() method will destroy the current buffer before redirecting the
client. In other words, if you build half of your page, then use  the sendRedirect()method,
the client will not see any content from the original Servlet.

 encodeRedirectURL()—Before  you  can  use  the  sendRedirect()  method,  you  should  use
this function to add the session id. This method will add the session id only if the page is
required to maintain state. The decision to add the id is purely up to the con­ tainer.

 encodeURL()—In  every  case  except  for  the  sendRedirect()  method,  you  should  use
encodeURL()to prepare the page refer­ ence. This method will add the session id if it is
required.  Because  the  decision  on  whether  state  is  required  is  different  for
sendRedirect()than  for  other  flow  control  methods  (such  as  an  HTML  form),  the
encodeURL()method uses different logic than encodeRedirectURL().

5. JSDK

JSDK is the Java Servlet Developers Kit. This is an add on to the regular JDK (Java Developers
Kit). The JSDK has the additional files needed in order to compile Java servlets. The latest version
of the JSDK is version 2.0. Included in the JSDK is a Java Servlet Runner program. The Servlet
Runner is a program that runs on your workstation, and allows you to test servlets you have written
without running a web server. Other files included are the several Java Servlet examples. Included
are the .java and .class files for testing purposes and to help you understand how the Java code is
implemented. Another important file that is included is the jsdk.jar file. This file includes the class
information necessary to compile the servlets.

Installing JSDK

The JDK includes the javac.exe program and other java library and class files that are necessary to
compile java code. Before you start to install the JSDK, install the JDK, then begin JSDK install.

Installing the JSDK is a very simple procedure. 

a. Run the .exe that you download from the http://java.sun.com web site, it will create some
temporary web files on your hard drive. 

b. It will then launch the installation script. You will be asked to specify the directory you
wish  to  have  the  files  copied  to.  As  in  the  JDK,  the  recommended  directory  includes  a
'period' in the directory name (ex. C:\JSDK.20). Change this to C:\JSDK20 instead to make
it easier when searching for the directory. 

c. After the software is installed, you will have a new subdirectory. In order to use both the
JDK and JSDK together, the java compiler (javac.exe) needs to know where the class files
are located. 

d. Put the bin directory for the JDK in the path. This will make it easy to find the javac.exe
program when compiling code. Second, add the jsdk.jar file to the classpath. This can be
done by adding a SET statement to the autoexec.bat file on your workstation (for Windows
95). 

e. The SET statement should read SET CLASSPATH = drive:JSDK install path\lib\jsdk.jar
(ex. SET CLASSPATH = C:\jsdk20\lib\jsdk.jar). 

f. Once this is done, there will be no problem compiling java servlets.

6. Servlet API

Servlets use classes and interfaces from two packages: javax.servlet and javax.servlet.http . The
javax.servlet package contains classes to support generic, protocol­independent servlets. These
classes  are  extended  by  the  classes  in  the  javax.servlet.http  package  to  add  HTTP­specific
functionality. The top­level package name is javax instead of the familiar java, to indicate that the
Servlet API is a standard extension. 

Every servlet must implement the javax.servlet.Servlet interface. Most servlets implement it by
extending  one  of  two  special  classes:  javax.  servlet.GenericServlet  or
javax.servlet.http.HttpServlet . A protocol­independent servlet should subclass GenericServlet,
while an HTTP servlet should subclass HttpServlet, which is itself a subclass of GenericServlet
with added HTTP­specific functionality. 

Unlike a regular Java program, and just like an applet, a servlet does not have a main() method.
Instead, certain methods of a servlet are invoked by the server in the process of handling requests.
Each time the server dispatches a request to a servlet, it invokes the servlet's service() method. 

A generic servlet should override its service() method to handle requests as appropriate for the
servlet. The service() method accepts two parameters: a request object and a response object. The
request  object  tells  the  servlet about  the  request,  while  the  response  object is  used  to  return  a
response. Figure below shows how a generic servlet handles requests. 

Figure 2. A generic servlet handling a request

In contrast, an HTTP servlet usually does not override the service() method. Instead, it overrides
doGet()  to  handle  GET  requests  and  doPost()  to  handle  POST  requests.  An  HTTP  servlet  can
override either or both of these methods, depending on the type of requests it needs to handle. The
service() method of HttpServlet handles the setup and dispatching to all the doXXX() methods,
which  is  why  it  usually  should  not  be  overridden.  Figure  below  shows  how  an  HTTP  servlet
handles GET and POST requests. 

Figure 3. An HTTP servlet handling GET and POST requests
An HTTP servlet can override the doPut() and doDelete() methods to handle PUT and DELETE
requests, respectively. However, HTTP servlets generally don't touch doHead() , doTrace() , or
doOptions() . For these, the default implementations are almost always sufficient. 

The remainder in the javax.servlet and javax.servlet.http packages are largely support classes. For
example,  the  ServletRequest  and  ServletResponse  classes  in  javax.servlet  provide  access  to
generic  server  requests  and  responses,  while  HttpServletRequest  and  HttpServletResponse  in
javax.servlet.http provide access to HTTP requests and responses. The javax.servlet.http package
also  contains  an  HttpSession  class  that  provides  built­in  session  tracking  functionality  and  a
Cookie class that allows you to quickly set up and process HTTP cookies. 

7. Servlet Packages: Working with Http Request and Response

Before we can start writing the first Servlet, we need to know some basics of HTTP ("HyperText
Transfer Protocol"), the protocol which is used by a WWW client (e.g. a browser) to send a request
to a Web Server.

HTTP is a request­response oriented protocol. An HTTP request consists of a request method, a
URI, header fields and a body (which can be empty). An HTTP response contains a result code and
again header fields and a body.

The  service  method  of  HttpServlet  dispatches  a  request  to  different  Java  methods  for  different
HTTP  request  methods.  It  recognizes  the  standard  HTTP/1.1  methods  and  should  not  be
overridden  in  subclasses  unless  you  need  to  implement  additional  methods.  The  recognized
methods are GET,  HEAD,  PUT, POST, DELETE, OPTIONS  and  TRACE.  Other  methods are
answered with a Bad Request HTTP error. An HTTP method XXX is dispatched to a Java method
doXxx, e.g. GET ­> doGet.

All  these  methods  expect  the  parameters  "(HttpServletRequest  req,  HttpServletResponse  res)".
The methods doOptions and doTrace have suitable default implementations and are usually not
overridden. The HEAD method (which is supposed to return the same header lines that a GET
method would return, but doesn't include a body) is performed by calling doGet and ignoring any
output that is written by this method. That leaves us with the methods doGet, doPut, doPost and
doDelete  whose  default  implementations  in  HttpServlet  return  a  Bad  Request  HTTP  error.  A
subclass  of  HttpServlet  overrides  one  or  more  of  these  methods  to  provide  a  meaningful
implementation.

The request data is passed to all methods through the first argument of type HttpServletRequest
(which is a subclass of the more general ServletRequest class). The response can be created with
methods of the second argument of type HttpServletResponse (a subclass of ServletResponse).
When you request a URL in a Web Browser, the GET method is used for the request. A GET
request does not have a body (i.e. the body is empty). The response should contain a body with the
response data and header fields which describe the body (especially Content­Type and Content­
Encoding). When you send an HTML form, either GET or POST can be used. With a GET request
the parameters are encoded in the URL, with a POST request they are transmitted in the body.
HTML  editors  and  upload  tools  use  PUT  requests  to  upload  resources  to  a  Web  Server  and
DELETE requests to delete resources.

8. Advantages over CGI

The traditional way of adding functionality to a Web Server is the Common Gateway Interface
(CGI), a language­independent interface that allows a server to start an external process which gets
information  about  a  request  through  environment  variables,  the  command  line  and  its standard
input stream and writes response data to its standard output stream. Each request is answered in a
separate process by a separate instance of the CGI program, or CGI script (as it is often called
because CGI programs are usually written in interpreted languages like Perl).

Servlets have several advantages over CGI:

1.  A  Servlet  does  not  run  in  a  separate  process.  This  removes  the  overhead  of  creating  a  new
process for each request.

2. A Servlet stays in memory between requests. A CGI program (and probably also an extensive
runtime system or interpreter) needs to be loaded and started for each CGI request.

3. There is only a single instance which answers all requests concurrently. This saves memory and
allows a Servlet to easily manage persistent data.

4. A Servlet can be run by a Servlet Engine in a restrictive Sandbox (just like an Applet runs in a
Web Browser's Sandbox) which allows secure use of untrusted and potentially harmful Servlets.

9. J2EE Servlet 2.x Specification

J2EE  is  just  a  specification  by  Java  that  aims  to  fulfil  software  needs  of  enterprise.  There  are
several APIs and technologies such as JSP, EJB etc which make J2EE a working platform. 

Specification is set of rules defined by any company which has to be followed by all the vendors.
Eg: The specification for three pin socket we see in our home defines the space between pin, lenght
of  pins  and width of pins.  All  3 pin socket  manufacturer follw  the specification. They can use
different  material  or  colour  and  also  can  price  extra  features  but  they  have  to  follow  the
specifcation. This solves lots of problem. We can use three pin manufacted by any company. 

Typical enterprise has following needs: 

a. Use existing legacy system along with new system 
b. Security 
c. Easy upgrade to latest technology 
d. Stability and reliability of software. 
e. Availability of software developers to support 
f. Develop complex softwares such as e­commerce websites. 

J2EE is one of the best choice for developing enterprise applications. Some advantages of using
J2EE for enterprise applications are listed below: 
a. Low cost 
b. Good Support from community 
c. Open Source 
d. Good documentation 
e. Availability of good J2EE developers. 
f. Low level services are already implemented
g. J2EE is a standardized and reliable software architecture 
h. It has huge user base and is popular in market. 
i. J2EE uses multi­tiered distributed application model.

 J2EE APIs and Technologies 

There are several APIs and technologies which make J2EE a working platform. These APIs and
technologies are listed below:: 

a. JDBC ( Java Database Connectivity) 
b. Servlets ( Server Side Component) 
c. JSP ( Java Server Pages) 
d. Java Mail ( Used to create email application) 
e. RMI ( Remote Method Invocation) 
f. Corba ( Comon object request broker object) 
g. EJB ( Enterprise Java Beans) 
h. JNDI ( Java Naming & Directory Interfaces) 
i. JMS ( Java Messaging Service) 
j. JAVA­XML ( JAXP, JAXM, JAXR, JAX­RPC, JAXB ) 
k. Connectors ( For Legacy systems). 
10.Writing small Servlet Programs

We start our venture into Servlet programming with the "Hello World" example,:

HelloClientServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class HelloClientServlet extends HttpServlet

   protected void doGet(HttpServletRequest req, HttpServletResponse res)

            throws ServletException, IOException

       {

      res.setContentType("text/html");

      PrintWriter out = res.getWriter();

      out.println("<HTML><HEAD><TITLE>Hello Client!</TITLE>"+

                  "</HEAD><BODY>Hello Client!</BODY></HTML>");

      out.close();

    }

    public String getServletInfo()

    {

      return "HelloClientServlet 1.0 by Stefan Zeiger";

   }

 }

When you compile this Servlet and run it by requesting a URL which is assigned to it in a Web
Browser it produces the following output:
Let's have a look at how the Servlet works.

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

The Servlet class is declared in line below. Our Servlet extends javax.servlet.http.HttpServlet, the
standard base class for HTTP Servlets.

public class HelloClientServlet extends HttpServlet

In lines below HttpServlet's doGet method is getting overridden.

protected void doGet(HttpServletRequest req, HttpServletResponse res)

 throws ServletException, IOException

 {

         ...

   }

In lines above we use a method of the HttpServletResponse object to set the content type of the
response  that  we  are  going  to  send.  All  response  headers  must  be  set  before  a  PrintWriter  or
ServletOutputStream is requested to write body data to the response.

   res.setContentType("text/html");

In line below we request a PrintWriter object to write text to the response message.

  PrintWriter out = res.getWriter();

ServletResponse.getWriter() is a new feature of JSDK version 2.0. If your Servlet engine does not
support  JSDK  2.0  you  can  replace  the  above  line  by  "ServletOutputStream  out  =
res.getOutputStream();". 
In lines below we use the PrintWriter to write the text of type text/html (as specified through the
content type).

     out.println("<HTML><HEAD><TITLE>Hello Client!</TITLE>"+

                 "</HEAD><BODY>Hello Client!</BODY></HTML>");

The PrintWriter gets closed in line below when we are finished writing to it.

     out.close();

This  line  is  included  for  completeness.  It  is  not  strictly  necessary.  The  Web  Server  closes  the
PrintWriter or ServletOutputStream automatically when a service call returns. An explicit call to
close() is useful when you want to do some post­processing after the response to the client has been
fully written. Calling close() tells the Web Server that the response is finished and the connection
to the client may be closed as well.

In lines below we override the getServletInfo() method which is supposed to return information
about the Servlet, e.g. the Servlet name, version, author and copyright notice. This is not required
for the function of the HelloClientServlet but can provide valuable information to the user of a
Servlet who sees the returned text in the administration tool of the Web Server.

 public String getServletInfo()

 {

     return "HelloClientServlet 1.0 by Stefan Zeiger";

  }

11.  Inter Servlet Collaboration

The inter­Servlet communication method which is described in this section can only be used with
Servlet  engines  which  implement  version  1.0  or  2.0  of  the  Servlet  API.  It  will  not  work  with
Servlet engines which comply strictly to version 2.1. This section shows how to call a method of
another Servlet. 

Servlets are not alone in a Web Server. They have access to other Servlets in the same Servlet
Context (usually a Servlet directory), represented by an instance of javax.servlet.ServletContext.
The ServletContext is available through the ServletConfig object's getServletContext method.

A Servlet can get a list of all other Servlets in the Servlet Context by calling getServletNames on
the  ServletContext  object.  A  Servlet  for  a  known  name  (probably  obtained  through
getServletNames) is returned by getServlet. Note that this method can throw a ServletException
because it may need to load and initialize the requested Servlet if this was not already done.

After  obtaining  the  reference  to  another  Servlet  that  Servlet's  methods  can  be  called.  Methods
which are not declared in javax.servlet.Servlet but in a subclass thereof can be called by casting the
returned object to the required class type.

Note  that  in  Java  the  identity  of  a  class  is  not  only  defined  by  the  class  name  but  also  by  the
ClassLoader by which it was loaded. Web servers usually load each Servlet with a different class
loader. This is necessary to reload Servlets on the fly because single classes cannot be replaced in
the running JVM. Only a ClassLoader object with all loaded classes can be replaced.

This means that classes which are loaded by a Servlet class loader cannot be used for inter­Servlet
communication.  A  class  literal  FooServlet  (as  used  in  a  type  cast  like  "FooServlet  foo  =
(FooServlet)context.getServlet("FooServlet")") which is used in class BarServlet is different from
the class literal FooServlet as used in FooServlet itself.

A way to overcome this problem is using a superclass or an interface which is loaded by the system
loader and thus shared by all Servlets. In a Web Server which is written in Java those classes are
usually located in the class path (as defined by the CLASSPATH environment variable).

Example. 

Servlet FooServlet wants to call the method public void bar() of Servlet BarServlet. Both Servlets
should  be  reloadable  so  the  Servlet  classes  cannot  be  loaded  by  the  system  loader.  Instead  we
define an interface BarInterface which defines the callable method and is loaded by the system
loader. BarServlet implements this interface. The Servlets are placed into the Servlet directory and
the interface into a directory in the class path.

public class FooServlet extends HttpServlet

    protected void doGet(HttpServletRequest req, HttpServletResponse res)

              throws ServletException, IOException

    {

      ...

      ServletContext context = getServletConfig().getServletContext();

      BarInterface bar = (BarInterface)context.getServlet("BarServlet");

      bar.bar();
      ..

    }

    ...

  }

  public interface BarInterface

  {

    public void bar();

  }

 public class BarServlet extends HttpServlet implements BarInterface

   public void bar()

   {

     System.err.println(""bar() called"");

   }

   ...

 }

Sharing Data Between Servlets 

This section shows how to share data between Servlets 

Version 2.1 of the Servlet API offers a new way of sharing named objects between all the Servlets
in a Servlet context by binding the objects to the ServletContext object which is shared by several
Servlets.

The ServletContext class has several methods for accessing the shared objects:
public void setAttribute(String name, Object object) adds a new object or replaces an old object by
the specified name. The attribute name should follow the same naming convention as a package
name  (e.g.  a  Servlet  com.foo.fooservlet.FooServlet  could  have  an  attribute
com.foo.fooservlet.bar).

Just like a custom ServletRequest attribute, an object which is stored as a ServletContext attribute
should  also  be  serializable  to  allow  attributes  to  be  shared  by  Servlets  which  are  running  in
different JVMs on different machines in a load­balancing server environment.

public Object getAttribute(String name) returns the named object or null if the attribute does not
exist.

In addition to the user­defined attributes there may also be predefined attributes which are specific
to the Servlet engine and provide additional information about a Servlet(Context)'s environment.

public  Enumeration  getAttributeNames()  returns  an  Enumeration  of  the  names  of  all  available
attributes.

public  void  removeAttribute(String  name)  removes  the  attribute  with  the  specified  name  if  it
exists.

The separation of Servlets into Servlet contexts depends on the Servlet engine. The ServletContext
object of a Servlet with a known local URI can be retrieved with the method public ServletContext
getContext(String uripath) of the Servlet's own ServletContext. This method returns null if there is
no Servlet for the specified path or if this Servlet is not allowed to get the ServletContext for the
specified path due to security restrictions.

12.  Session Management

Since there is no way for an HTTP client to signal that it no longer needs a session, each session
has  an  associated  timeout  so  that  its  resources  can  be  reclaimed.  The  timeout  period  can  be
accessed  with  a  session's  [get|set]MaxInactiveInterval  methods.  You  can  also  set  the  timeout
period in deploytool: 

1. Select the WAR. 

2. Select the General tab. 

3. Enter the timeout period in the Advanced box. 

To ensure that an active session is not timed out, you should periodically access the session via
service methods because this resets the session's time­to­live counter. 
When  a  particular  client  interaction  is  finished,  you  use  the  session's  invalidate  method  to
invalidate a session on the server side and remove any session data. 

The following methods are part of the HttpSessionobject:

 MaxInactiveInterval()—The  session  object  has  get  and  set  methods  for  controlling  the
maximum time (in seconds) between user requests. If a user does not perform a request in
that time, the session object is destroyed. The default setting is container­ specific, but is
generally 1,800 seconds (30 minutes).
 invalidate()—The  invalidate()method  will  destroy  the  ses­  sion  object  and  release
references to objects stored in the session attributes.
 getId()—Session  IDs  provide  a  temporary  primary  key  that  you  can  use  to  identify  a
session uniquely. The session id is generated by the JSP container and may use any system
the vendor chooses. For example, Tomcat generates a ten­character al­ phanumeric id such
as “1juorqf451”. ids may be reused, al­ though active sessions will never share ids. The id
is usually sent to the client as a cookie or part of the query string to help the con­ tainer
maintain the session link to a particular HttpSession object.
 getCreationTime() and getLastAccessedTime()—These meth­ ods will return date objects
that tell you when the session was created and when it was last accessed.

13.  State on web

State refers to the ability to save information. An application that “remembers” data from one
page to the next is said to “maintain state” or to be “stateful.” A basic HTML page does not retain
information between HTTP requests and is thus “stateless.” Maintaining state is a par­ ticularly
important  concept  for  useful  web  applications  such  as  e­commerce  systems.  State  can  be
maintained in any number of ways, from client­side cookies to database tables. State can also last
for any length of time, from a single page access to a single user session to permanent storage.

Scope
Scope  is  often  described  as  the  lifespan  of  state,  or  the  length  of  time  over  which  state  is
maintained and can be accessed. Servlets and JSP have four basic levels of scope:

 Page—The page scope is defined as the time between the initiali­ zation of a particular
page and its destruction. Data stored in the page scope retains state as long as the page
remains active. Page scope is only available for JSPs.
 Session—The session scope consists of a single interactive con­ versation between a client
and  a  web  server.  Data  stored  in  the  session  scope  maintains  state  until  the  session  is
destroyed  through  timeout,  or  through  closing  the  browser(s)  that  accessed  the  site,  or
through  a  communications  failure.  The  session  scope  is  a  very  common  place  to  store
information that relates to a par­ ticular user (such as authentication) or a particular web
experience (such as a shopping cart).
 Application—The application scope relates to all of the Servlets and JSPs that are part of a
Java  web  application.  This  scope  tran­scends  individual  users  and  is  often  used  for  hit
counters  and  support  systems  (e.g.,  JDBC  connection  pools).  Application  scope  is
maintained until the server is restarted or the application is redeployed.
 Request—The request scope relates specifically to the request that launched the page. A
request scope can be forwarded through several Servlets and JSPs and maintains its state
until a response object is sent in reply to the client.

14. Different ways to track sessions

This section shows how to use Session Tracking capabilities 

Session Tracking allows a Servlet to associate a request with a user. A session can extend across
requests and connections of the stateless HTTP. Sessions can be maintained in two ways:

By using Cookies. A Cookie is a string (in this case that string is the session ID) which is sent to a
client to start a session. If the client wants to continue the session it sends back the Cookie with
subsequent requests. This is the most common way to implement session tracking.

By rewriting URLs. All links and redirections which are created by a Servlet have to be encoded
to include the session ID. This is a less elegant solution (both, for Servlet implementors and users)
because the session cannot be maintained by requesting a well­known URL oder selecting a URL
which was created in a different (or no) session. It also does not allow the use of static pages. All
HTML pages which are sent within a session have to be created dynamically.

Our next Servlet manages a virtual shopping cart. Users can add various items to their shopping
cart via HTML forms. The shopping cart contents are stored on the server and each user gets his
own shopping cart which is selected automatically whenever he makes a request to the Servlet.

In the simplified version that we implement in class ShoppingCartServlet there are only two kinds
of items, named FOO and BAR. By pressing a button in an HTML form a single FOO or BAR item
can be put into the shopping cart. There's another button to see the current contents of the shopping
cart and a button to order the selected items, thus clearing the shopping cart.

The  first  version  of  the  Servlet,  called  ShoppingCartServlet,  which  works  with  Cookie­style
sessions only, consists of the two standard methods, doGet and doPost:

A form with the buttons is created by the Servlet's doGet method.
    protected void doGet(HttpServletRequest req, HttpServletResponse res)

              throws ServletException, IOException

    {

      res.setContentType("text/html");

      PrintWriter out = res.getWriter();

      out.print("<HTML><HEAD><TITLE>Online Shop</TITLE>"+

                "</HEAD><BODY><FORM METHOD=POST>"+

                "<INPUT TYPE=SUBMIT NAME=foo VALUE="+

                "\"Put a FOO into the shopping cart\">"+

                "<INPUT TYPE=SUBMIT NAME=bar VALUE="+

                "\"Put a BAR into the shopping cart\">"+

                "<INPUT TYPE=SUBMIT NAME=see VALUE="+

                "\"See the shopping cart contents\">"+

                "<INPUT TYPE=SUBMIT NAME=buy VALUE="+

                "\"Buy the shopping cart contents\">"+

                "</FORM></BODY></HTML>");

      out.close();

    }

Alternatively, it could also come from a static HTML page.

The  doPost  method  processes  the  form  data  which  is  sent  by  a  client  in  response  to  the  form
created by doGet.

    protected void doPost(HttpServletRequest req, HttpServletResponse res)

              throws ServletException, IOException

    {

      String msg;
      HttpSession session = req.getSession(true);

      if(session.isNew())

      {

        session.putValue("foo", new int[] { 0 });

        session.putValue("bar", new int[] { 0 });

      }

      int[] foo = (int[])session.getValue("foo");

      int[] bar = (int[])session.getValue("bar");

      if(req.getParameter("foo") != null)

      {

        foo[0]++;

        msg = "Bought a FOO. You now have "+foo[0]+".";

      }

      else if(req.getParameter("bar") != null)

      {

        bar[0]++;

        msg = "Bought a BAR. You now have "+bar[0]+".";

      }

      else if(req.getParameter("buy") != null)

      {

        session.invalidate();

        msg = "Your order for "+foo[0]+" FOOs and "+bar[0]+

          " BARs has been accepted. Your shopping cart is empty now.";

      }

      else
      {

        msg = "You have "+foo[0]+" FOOs and "+bar[0]+

          " BARs in your shopping cart.";

      }

     res.setContentType("text/html");

      res.setHeader("pragma", "no­cache");

      PrintWriter out = res.getWriter();

      out.print("<HTML><HEAD><TITLE>Shopping Cart</TITLE></HEAD><BODY>");

      out.print(msg);

      out.print("<HR><A HREF=\"");

      out.print(req.getRequestURI());

      out.print("\">Back to the shop</A></BODY></HTML>");

      out.close();

    }

First we get the HttpSession object which is associated with the request by calling req.getSession.
The argument true forces the creation of a new session if the request doesn't contain a valid session
key.

Note: Although getSession is a method of HttpServletRequest and not of HttpServletResponse it
may modify the response header and therefore needs to be called before a ServletOutputStream or
PrintWriter is requested.

If the session is indeed new (determined by calling HttpSession's isNew() method) we add some
custom data to the session: Two counters, one for the FOOs and one for the BARs in the shopping
cart. The session object can be used like a Dictionary. That means we can only add Objects, not
instances  of  primitive  types  like  int.  We  could  use  an  instance  of  java.lang.Integer  for  each
counter,  but  these  objects  are  immutable  which  makes  incrementing inefficient  and  difficult  to
implement.  Instead  we  use  an  array  of  int  (int[])  with  only  one  element  as  a  mutable  wrapper
object. The element is initialized to 0.

Next we retrieve the values for "foo" and "bar" from the session, no matter if they were just added
or carried over from a previous request.
In the ListManagerServlet both buttons had the same name but different values so we could use
getParameter to retrieve the value from the request and then do a string compare to the possible
values. This time we use a  different approach which can be implemented more efficiently. All
buttons have different names and we can find out which button was used to submit the form by
checking which name has a non­null value.

A new FOO or BAR item can be put into the shopping cart by simply incrementing the counter in
the  array.  Note  that  the  array  does  not  need  to  be  put  back  into  the  session  because  it  has  not
changed itself, only the contents have been modified.

When  the  user  chooses  to  buy  the  contents  of  the  shopping  cart  we  call  session.invalidate()  to
delete  the  session  on  the  server  side  and  tell  the  client  to  remove  the  session  ID  Cookie.  The
session data is lost and when a new POST request is made to the Servlet, a new session will be
created.

The rest of the doPost method is basically the same as in the ListManagerServlet.

15.  Security Issues. 

Security is the science of keeping sensitive information in the hands of authorized users. On the
web, this boils down to three important issues: 

Authentication 

Being able to verify the identities of the parties involved

Confidentiality 

Ensuring that only the parties involved can understand the communication 

Integrity 

Being  able  to  verify  that  the  content  of  the  communication  is  not  changed  during
transmission 

A client wants to be sure that it is talking to a legitimate server (authentication), and it also want to
be  sure  that  any  information  it  transmits,  such  as  credit  card  numbers,  is  not  subject  to
eavesdropping  (confidentiality).  The  server  is  also  concerned  with  authentication  and
confidentiality.  If  a  company  is  selling  a  service  or  providing  sensitive  information  to  its  own
employees, it has a vested interest in making sure that nobody but an authorized user can access it.
And both sides need integrity to make sure that whatever information they send gets to the other
party unaltered. 

Authentication,  confidentiality,  and  integrity  are  all  linked  by  digital  certificate  technology.
Digital  certificates  allow  web  servers  and  clients  to  use  advanced  cryptographic  techniques  to
handle  identification  and  encryption  in  a  secure  manner.  Thanks  to  Java's  built­in  support  for
digital certificates, servlets are an excellent platform for deploying secure web applications that
use digital certificate technology. We'll be taking a closer look at them later. 

Security is also about making sure that crackers can't gain access to the sensitive data on your web
server. Because Java was designed from the ground up as a secure, network­oriented language, it is
possible to leverage the built­in security features and make sure that server add­ons from third
parties are almost as safe as the ones you write yourself. 

Review Questions

1. Explain lifecycle of a Servlet. Also write a simple servlet program. (UTU, Odd sem 2011­
12)

2. Explain  different  methods  present  in  ServletRequest  and  ServletResponse  interfaces.  (


UTU, Odd sem 2011­12)

3. What  are  the  different  techniques  of  session  tracking  management?  Explain  in  brief.  (
UTU, Odd sem 2011­12)

4. What do you mean by servlet? List advantages of servlet over CGI. (UTU, Odd sem 2011­
12)

5. Explain the following with suitable example: 

i. Handling HTTP GET Requests

ii. Handling HTTP POST Requests        (UTU,  Odd  sem


2011­12)

6. List all the interfaces and classes contained in the pack javax.servlet.http package. Give
their description also. (UTU, Odd sem 2011­12)

You might also like