Java Web Technology Unit-4

Document Sample
Java Web Technology Unit-4 Powered By Docstoc

Definition: A Servlet is a server side program which is loaded and executed by the Web server.
Servlets are pure java programs which run under the address space of JVM. Servlets accepts a
request from a client, perform some tasks and returns the results to the client using HTTP
          A client makes a request through HTTP.(protocol)
          Web Server receives this request for a service and its loads the servlet into its address
           space and runs it. The web Server initializes the servlet. And forward the request to the
          The servlet receives the HTTP request from the Web Server and done some processing.
          The servlet will return the response back to the Web Server.
          The Web Server will forward the response to the client.

                            1                                  2                            3

   Web Browser                           Web Server                        Servlet
                            6                                   5                          4

          Here, the web server loads the servlets only once and the servlet can maintains the
services to the client. (A thread based application).Since the servlets are running the address
space of the Web Server, the code will not go out of the boundaries. Hence servlets are more

How a Servlet Works

          A servlet is loaded by the servlet container the first time the servlet is requested. The
servlet then is forwarded the user request, processes it, and returns the response to the servlet
container, which in turn sends the response back to the user. After that, the servlet stays in
memory waiting for other requests—it will not be unloaded from the memory unless the servlet
container sees a shortage of memory. Each time the servlet is requested, however, the servlet
container compares the timestamp of the loaded servlet with the servlet class file. If the class file
timestamp is more recent, the servlet is reloaded into memory. This way, you don't need to
restart the servlet container every time you update your servlet.


Web Server

        A Web Server is an environment where the servlets runs. A web server supports Servlet
API’s and provides various services to the client programs. A service is an implementation of
specific protocol such as HTTP, SMTP and FTP.when a request is made to the server it initiates
or loads the servlets into its address space and create a pool of threads which in turns provides
the services to the client programs. The web Server consists the servlet container or Servlet
Engines which is responsible for running the servlets.

Servlet Container / Servlet Engine: A servlet container is run time environment to provide the
life cycle of servlet(i.e. loading and unloading the servlet).It is the container which loads the
servlet delegates the requests to and from the servlets. The following are the services of the
    Communication support
    Multithreading support
    Security
    Session Management.

                          Container /                    Servlet

                                        Web Server (TOMCAT)

Servlet advantages over CGI


   1. Efficient: A servlet initialization code is executed only the first time the Web server
          loads it. After the servlet is loaded, handling new requests is only a matter of calling a
          service method. This is a much more efficient technique than loading a completely new
          executable with every request.
   2. Persistent: Servlets can maintain state between requests. When a servlet is loaded, it
          stays resident in memory while serving incoming requests. A simple example of this
          would be a Vector that holds a list of categories used in an online catalog. Taking
          advantage of the persistent characteristics of servlets can improve your applications
          performance drastically.
   3. Portable: Servlets are developed using Java; therefore, they are portable. This enables
          servlets   to be moved to a new operating system without changing the source.
   4. Robust: Because servlets are developed with access to the entire JDK, they are very
          powerful and robust solutions. Java provides a very well-defined exception hierarchy for
          error handling. It has a garbage collector to prevent problems with memory leaks. In
          addition, it includes a very large class library that includes network support, file support,
          database access, distributed object components, security, and many other classes.
   5. Extensible: Another advantage servlets gain by being developed in an object-oriented
          language like Java is they can be extended and polymorphic into new objects that better
          suit your needs.
   6. Secure: Servlets run on the server side, inheriting the security provided by the Web
          server. Servlets can also take advantage of the Java Security Manager.

Setting up the Servlet and JSP Environment: Setting up the JSP environment is an important
step to run the servlet/JSP programs. It involves two steps
1.Installing the Java Development Kit(JDK) :- The following steps to install the JDK

       Download the latest version JDK from the internet using the sun microsystem website
          Double click the JDK installer to start installing the JDK,which prompts many steps
           until you installing JRE and finally selecting the browser.
       setting up the Environment variables under window XP/NT/2000. as follows
               a. Right click the myComputer and goto propertiesAdvancedEnvironment.


              b. Click the new button in the User Variables section to create the PATH variable.
                   C:\Program Files\Java\jdk1.5.0\bin

              c. To set JAVA_HOME ,again click new button and Type JAVA_HOME in
                 name and C:\Program Files\Java\jdk1.5.0 in Variable Value.

              d.    Finally click OK button to finish setting.

2. Installing The Tomcat server:-Tomcat is a pure                open-source Java-based   webserver
developed by Apache Software Foundation which contains container to support for the Servlet
and JSP specification. You can download Tomcat server at free of cost in binary format available
at order to use webserver we must install
JRE(Java Runtime Environment) which is required              by the JSP which includes the java
compiler(javac).Before you install and run tomcat , make sure that the JAVA_HOME
environment variable is set to the installation directory. The installation includes many steps
click next to continue which prompts configuration (port number(8080),username, password and
JRE directory path folder).

Startup:-If you have installed tomcat successfully, then you must set the CATALINA_HOME
environment variables in User Variables which includes the bin directory path consists of startup
,shutdown bat files. C:\Program Files\Apache Software Foundation\Tomcat5.0\bin. Finally
select “monitor tomcat” in start menuAll programsApache Tomcat 5.5.You would see a
Tray Icon ,right click on it and pop-up menu is appear and start the tomcat server in the


Testing Tomcat server :- To verify that tomcat installed successfully and properly to respond
request start tomcat and type the Following URL http://localhost:8080 in the browser and you
will see the following page as shown below.

                                Tomcat Directory Structure

               Directory Name                                      Description
Webapps                                        Contains servlets and Jsps to be served by
Bin                                            Contains startup, shutdown scripts and other
Common                                         Contains common classes for servlet and JSP
Conf                                           Contains server configuration files (server.xml,
Logs                                           Contains tomcat log files
Server                                         Contains server’s active file.
Shared                                         Contains classes and resources shared among
Temp                                           Used by JVM for temporary files
Work                                           Contains files and directories created by jsp
                                               container. This directory holds the servlet
                                               equivalent of jsp’s
Running.txt                                    Contains details about how to get started with


Notice.txt                                           Contains general information about the product.

                                            Web Application

web application is a collection of cooperating resources such as servlets, jsp, HTML, images,
supporting classes and configuration structured in a specific manner. A web application goes
through many phases during its life time.
    Development Phase
                Creating the Directory Structure
                Creation of Servlet and JSP files
                Creation of Deployment Descriptor file called web.xml
                Creation of HTML files.
                Creation of Java classes
                creation of any other supporting files(CSS,JS,Images).
    Deployment Phase
    Running Phase

                             Directory Structure of web application





                        Jsps/html                  WEB-INF                  web.xml

                                                                       Tags Files


MyApplThis is a root directory of the web application
WEB-INFIt contains sub directories such as classes, lib, web.xml which cannot be accessed
directly by the user.
classesThis include supporting classes and interfaces(.CLASS FILES)
libThis includes third party .jar files such as struts.jar,servlet-api.jar,log4j.jar etc and these
classes will be automatically available to your web application
web.xmlIt is a deployment descriptor configuration file which includes necessary information
for your servlets and JSP pages.
Deployment Phase: Refer the above topic Deployment descriptor.
Running Phase: Running phase involves, calling the jsp pages in their context path for example
in our application (above)MyAppl(root directory) e.g:

Servlet Life Cycle


       The life cycle of a Java servlet is a very simple object-oriented design. It describes how
the servlet loaded, initialize, provide services and destroyed(garbage collected). The Life Cycle
of a servlet is managed by the container of the server. The Servlet interface defines the following
life cycle methods.

   1. init() :-The init() method is where the servlet’s life begins. It is called by the server
       immediately after the servlet is instantiated. It is called only once. In the init() method,
       the servlet creates and initializes the resources that it will be using while handling
       requests. The init() method’s signature is defined as follows:

                 public void init(ServletConfig config) throws ServletException;

The init() method takes a ServletConfig object as a parameter. You should save this object so
that it can be referenced later. The most common way of doing this is to have the init() method
call super.init(), passing it the ServletConfig object. You will also notice that the init() method
can throw a ServletException. If, for some reason, the servlet cannot initialize the resources
necessary to handle requests, the init() method should throw a ServletException.

   2. service():- The service() method handles all requests sent by a client. It cannot start
       servicing requests until the init() method has been executed. You will not usually
       implement this method directly, unless you extend the GenericServlet abstract class.

The most common implementation of the service() method is in the HttpServlet class. The
HttpServlet class implements the Servlet interface by extending GenericServlet. The signature of
the service() method is shown in the following:

public void service(ServletRequest       req, ServletResponse res)throws ServletException,

The service() method implements a request and response paradigm. The ServletRequest object
contains information about the service request, encapsulating information provided by the client.
The ServletResponse object contains the information returned to the client.


    3. destroy():-This method signifies the end of a servlet’s life. When a service is being shut
        down, it calls the servlet’s destroy() method. This is where any resources that were
        created in the init() method should be cleaned up. If you have an open database
        connection, you should close it here. This is also a good place to save any persistent
        information that will be used the next time the servlet is loaded. The signature of
        destroy() is very simple, but I have displayed it as follows just to complete the picture:

                                       public void destroy ();

Java Servlet Life Cylce Program
import javax.servlet.*;
public class LifeCycle extends GenericServlet
        public void init(ServletConfig config)
        public void service(ServletRequest req, ServletResponse res) throws IOException,
                   System.out.println("In Service Methods");
                   PrintWriter out = res.getWriter();
                   out.println("<CENTER> SERVLET LIFE CYCLE PROGRAM</CENTER>");
        public void destroy()

HTTP Requests, Responses, and Headers

        HTTP is a simple, stateless protocol. A client, such as a web browser, makes a request,
the web server responds, and the transaction is done. When the client sends a request, the first
thing it specifies is an HTTP command, called a method, which tells the server the type of action
it wants performed. The first line of the request specifies the address of a document (a URL) and
the version of the HTTP protocol it is using. For example:
                                   GET /index.html HTTP/1.0


       This request uses the GET method to ask for the document named index.html, using
HTTP Version 1.0. After sending the request, the client can send optional header information to
tell the server extra information about the request, such as what software the client is running and
what content types it understands.

       After the client sends the request, the server processes it and sends a response. The first
line of the response is a status line specifying the version of the HTTP protocol the server is
using, a status code, and a description of the status code. For example:
                                        HTTP/1.0 200 OK

       This status line includes a status code of 200, which indicates that the request was
successful, hence the description OK. Another common status code is 404, with the description
Not Found


The Servlet API consists classes, interfaces and methods used to create Servlet application. It
of two packages. 1. javax.servlet. 2. javax.servlet.http

The javax.servlet package consists the following classes and interface.
    interface Servlet
    interface ServletConfig
    interface ServletContext
    interface ServletRequest
    interface ServletResponse
    interface SingleThreadModel
    class GenericServlet
    class ServletException

The javax.servlet.htttp package consists the following classes and interface.
    interface HttpServletRequest
    interface HttpServletReponse
    interface HttpSession
    class Cookie
    class HttpServlet

                           Exploring the javax.servlet package


The Servlet Interface: The Methods defines in servlet interface are shown below.
interface Servlet
  void destroy();
  ServletConfig getServletConfig();
  String getServletInfo();
  void init(ServletConfig config) throws ServletException, UnavailableException
  Service(ServletRequest req,Servlet res) throws ServletException, IOexception

   o void destroy() : This method is called when the servlet is unloaded from the address
        space of the webserver.
   o ServletConfig getServletConfig() : It return the Servletconfig object which contains all
        the initialization parameters.
   o String getServletInfo() : It returns the information about the servlet as a string.
   o void init(ServletConfig config) throws ServletException : This method is called when
        the servlet is initialized. The initialization parameters are obtained from servletConfig
        object. It throws ServletException when the servlet is not initialized properly.
   o service(ServletRequest req,Servlet res) :This method is used to process the client
        request and send the response back to the client.

The ServletConfig Interface: This interface is implemented by the server. The following are the
methods in this interface.

interface ServletConfig
  ServletContext getServletContext();
  String getInitParameter(String param);
  Enumeration getInitParameterNames();

    o ServletContext getServletContext (): It returns the context of the servlet.
      o String getInitParameter (String param): It returns the value of the initialization
         parameter whose name is param.
      o Enumeration getInitParameterNames(): It returns the name of all the initialization
         parameters into Enumeration object.


The ServletContext Interface: This interface is implemented by the server. It is the
environment where the servlet runs. It consists methods which return all information about the
environment about the servlet. All this information is maintained by the container in
javax.servlet.servletContext object. The context initialization parameters for a web application is
specified in the <context-param> element of the deployment descriptor. To read the parameters(
e.g. name) use the following method.

interface ServletContext
  Object getAttribute(String attrib);
  String getMimeType(String file);
  Servlet getServlet(String sname) throws ServletException;
  Enumeration getServletNames();
  void log(String str)

     Object getAttribute(String attrib) : method returns the value of the attribute as an
       String getMomeType(String file) : method returns the MIME type of a file .
     Servlet getServlet(String sname) : method returns name of the servlet by sname.
     Enumeration getServletNames() : method all the names of servlets as an Enumeration
     void log(String str) : it writes the string object str to the server log file.

                        Difference between ServletConfig and ServletContext

                    ServletConfig                                     ServletContext
contains configuration information for an           contains environment details of web
individual servlets.                                application which consists several servlets.
It is used only one per servlet                     It is used per web application
It can be used to pass information to a             It can be used to communicate with other
servlet during initialization.                      servlet or container by using methods defined
                                                    by it.
Initialization parameters are defined in            Initialization parameters are defined in
<init-param> element of the web.xml.                <context-param> element of the web.xml.


The ServletRequest Interface: This interface is enables a servlet to get the information about
client request. Following are the methods.
interface ServletRequset
  String getAttribute(String attrib);
  String getCharacterEncoding();
  int getContentLength();
  int getContentType();
  String getParameter();
  String getParameterNames();
  String[] getParameterValues();
  String getProtocol();
  String getRemoteAddr();
  String getRemoteHost();
  String getServletNames();
  String getServerPort();

The ServletResponse Interface: This interface is enables a servlet to form a response to the
client. The following are the methods.

interface ServletRequset
    String getCharacterEncoding();
    void setContentLength(int size);
    void setContentType(String type);
    String getServerPort();

The GenericServlet class :This class is defines in javax.servlet Package that implements servlet
interface and servletConfig. The methods of Generic Servlet class provides basic
implementation for servlet life cycle methods init (), service () and destroy ();

class GenericServlet implements Servlet,ServletConfig,Serializable
   void destroy()
   String getInitparameter(String name)
   Enumeration getInitParameterNames()
   ServletConfig getServletConfig();
   ServletContext getServletContext();
   String getServletInfo();


    void init(ServletConfig config) throws ServletException
    void service(ServletRequest req , ServletResponse res) throws ServletException, IOException
    void log(String str);

        String getInitParameter(String name) : It returns the value of the Initialization
        Enumeration getInitParameterNames() : It returns all the names of the initialization
         parameters as an enumeration object.

package com;
import javax.servlet.*;
public class ServletExample extends GenericServlet
  public void service(ServletRequest request, ServletResponse response)
     throws ServletException, IOException
        PrintWriter out = response.getWriters);
       out.println("<body bgcolor='green'>");
       out.println("<center><h1>WELCOME TO SERVLET EXAMPLE …");


            The web.xml file in the WEB-INF directory is known as a deployment descriptor.
This file contains configuration information about the web app in which it resides. The
deployment descriptor file controls servlet registration, URL mappings, welcome files, and
MIME types, as well as advanced features like page-level security constraints and how a servlet
should behave in a distributed environment.

                                A Simple Deployment Descriptor

<?xml version="1.0" encoding="ISO-8859-1"?>
<! DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"



            The first line declares this is an XML 1.0 file containing characters from the standard
ISO-8859-1 (Latin-1) charset. The second line specifies the DTD for the file. The rest of the text,
everything between <web-app> and </web-app>, provides information to the server about this
web application. This simple example registers our HelloWorld servlet under the name Hello.
The registered name is held between the <servlet-name> tags; the class name is placed within
the <servlet-class> tags. The <servlet> tag holds the <servlet-name> and <servlet-class> tags
together. This deployment descriptor adds a <servlet-mapping> entry indicating to the server
that the servlet named Hello should handle all URLs matching the pattern /feroz/*. If this web
app is mapped to the root path "/ ", this lets the HelloWorld servlet handle requests for incoming


Reading the Initialization Parameters using Servlets

In servlet, the interface ServletConfig provides methods to access the initialization parameters.
The initialization parameters of servlets are defined in web.xml. the initialization parameters
reads by container from the web.xml file to create ServletConfig object and passed this object as
parameter to the init() method of servlet.


getServletConfig().getInitParameters(“name”) : returns the parameters values of name


Example : A web.xml file which consists the initialization parameters

<display-name>READING -INITIALIZATION-PARAM</display-name>
            <param-name> Name :</param-name>
            <param-value>MD FEROZ </param-value>
            <param-name>ROLL NUMBER :</param-name>
            <param-value>02661A1214 </param-value>

A servlet program to read the initialization parameters from web.xml files above

public class ServletInitialization extends GenericServlet
  public void service(ServletRequest request, ServletResponse response) throws
            PrintWriter out = response.getWriter();
            StringBuffer buffer = new StringBuffer();
            out.println("<body bgcolor='pink'>");
            out.println("<h2><u>READING THE INITIALIZATION
            Enumeration parameters =getServletConfig().getInitParameterNames();
                String parameter =(String)parameters.nextElement();
                out.println("<br>"+parameter+" :");



Reading the ServletRequest Parameters

The Servlet takes the client request as object and process the request and response back to the
client. It reads the parameters from the HTML form and process its request.

<title> Request form </title>
<body bgcolor="#99cccc">
<form method="post" action="RequestServlet">
Name :<input type="text" name="name" size="15"/>
<input type="submit" value="submit"/>


package com.feroz;
import javax.servlet.*;


import java.util.*;
public class RequestServlet extends GenericServlet
   public void service(ServletRequest req,ServletResponse res) throws ServletException,
                PrintWriter out = res.getWriter();
               out.println("<h2>Request Parameters Informations</h2>");
               out.println("<br>You Entered Name : "+req.getParameter("name"));
               out.println("<br>ServletName : "+req.getServletName());
               out.println("<br>Server Port : "+req.getServerPort());
               out.println("<br>Remote Address : "+req.getRemoteAddr());
               out.println("<br>Content Length : "+req.getContentLength());
               out.println("<br>Protocol : "+req.getProtocol());

                        Exploring the javax.servlet.http package

The javax.servlet.htttp package consists the following classes and interface.

      Interface HttpServletRequest
      Interface HttpServletReponse
      Interface HttpSession
      Class Cookie
      Class HttpServlet

The Interface HttpServletRequest: This interface enables a servlet to obtain information about
a client request. It is implemented by the server. The following are the methods of this interface.

public interface HttpServletRequest extends ServletRequest
  String getAuthType()
  Cookie[] getCookies()
  long getDateHeader(String name)
  String getHeader(String name)
  String getMethod()
  String getQueryString()
  String getRemoteUser()
  String getRequestedSessionId()
  String getRequestURL()


    HttpSession getSession(boolean new)

        String getAuthType() : It returns the Authentication scheme.(BASIC,DIGEST).
        Cookie[] getCookies() : it returns array of cookie.
        Long getDateHeader(String name) : It returns a long value that represents the number
         of milliseconds since the mid-night of january 1. 1970,GMT till date represented by
        String getHeader () : It returns the value of the header with name name as string.
        String getMethod() : It returns the HTTP method for the client request. i.e
        String getQueryString() : It returns the query string in the URI. The part of the URI
         after the query character ? is called QueryString.In QueryString (+) specifies space.
        String getRemoteUser() : It returns the name of the user that makes the request.
        String getRequestedSessionId() : It returns the session ID specifies by the client.
        HttpSession getSession(boolean new) : This method             returns the current session
         associated with the user making the request. If there is no session, this method creates the
         session when new=true;

The HttpServletResponse Interface :This interface enables a servlet to formulate response to a
client. It is implemented by the server. The following are the methods of this interface.

interface HttpServletResponse extends ServletResponse
   void addCookie(Cookie c)
   String encodeURL(String url)
   void sendRedirect(String url)
   void sendError(int code,String name)
   void setDateHeader(String name,long msec)
   void setStatus(in code,String name)

        void addCookie(Cookie c) : This methods adds Cookie c object to HTTP response
        String encodeURL(String url) : this method determines whether the session ID must be
         encoded in the URL identified as url.
        void sendRedirect(String url) : it redirects the response to the specified location.


      void setDateHeader(String name, long msec ) : methods adds name field to the
       response header with date value equal to msec.
      void sendError(int code,String name) : it sends the error code to the client and the
       message as name.
      void setStatus(int code,String name) : This method sets the status and message for the
       response to code and string respectively.

The HttpServlet class : This class is used commonly for developing servlets that process
requests and response using HTTP. The following are the methods of this class.

class HttpServlet extends GenericServlet implements Servlet,Serializable
   public HttpServlet();

   public void service(HttpServletRequest req,HttpServletResponse) throws
   ServletException, IOException

  public void doGet(HttpServletRequest req,HttpServletResponse) throws
  ServletException, IOException

  public void doPost(HttpServletRequest req,HttpServletResponse) throws
  ServletException, IOException

  public void doDelete(HttpServletRequest req,HttpServletResponse) throws
  ServletException, IOException

  public void doTrace(HttpServletRequest req,HttpServletResponse) throws
  ServletException, IOException

  public void doOptions(HttpServletRequest req,HttpServletResponse) throws


1) public void service( ) : This methods dispatches requests to other methods such as doGet and
doPost based on the request.

2) public void doGet( ) : This method get the request parameters from client request dispatches
from service method.

3) public void doPost( ) : This method send the response to the client request dispatches from
service( ) method.

4) public void doDelete( ) : The service( ) method dispatches all the HTTP DELETE requests to
this method.

5) public void doTrace( ) : The service( ) method dispatches all the HTTP TRACE requests to
this method.

6)public void doOptions( ) : The service( ) method dispatches all the HTTP OPTIONS requests
to this method.

                          GenericServlet class v/s HttpServlet class

The HttpServlet class is defined javax.servlet.http package is an extension of   GenericServlet
class. The methods of Generic class are overrides in HttpServlet i.e. when a client makes a
request to a servlet. The servlet invoke the service() method .The service() method in turn
invoke either doGet() or doPost() methods based the client request. This package consists
classes which supports Cookie and Session to track the client request.

Example to demonstrate the use of GET & POST Method

<title> get method </title>
<body bgcolor="#99cccc">
<form action=" GetServlet ">
 <center><b>color : </b>
 <select name="color" size="1">
   <option value="red">RED</option>
            <option value="green">GREEN</option>
            <option value="blue">BLUE</option>



import javax.servlet.*;
import javax.servlet.http.*;
public class GetServlet extends HttpServlet
  public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,

              String color = req.getParameter("color");
              PrintWriter out = res.getWriter();
              out.println("<b>Your Favourite Color is : ");

Note : The same above use to demonstrate the POST method but we have explicitly mention the
POST method in <FORM> tag and in POST method the Query String in not appended in the
URL bar where as in GET method it appends.

Invoking Servlet using HTML

<title>form control </title>
<body bgcolor="#ffcccc">
<form name="registration" action="feroz/Registration" method=”post”>
 <table border="1" width="60%" height="50%">
 <td> Name</td>
 <td><input type="text" value="md feroz" size="15" name=”Name”/></td>


  <td><input type="password" value="md feroz" size="15" maxlength="15"
  <td><textarea cols="12" rows="3" value="shadnagar" name=”Address”/></textarea></tr>
  <td><input type="checkbox" name="skill" value="html"/>HTML
       <input type="checkbox" name="skill" value="java"/>JAVA
       <input type="checkbox" name="skill" value=".net"/>.NET
    <td><input type="radio" name="gender" value="male" checked />MALE
         <input type="radio" name="gender" value="female"/>FEMALE
<td colspan="2" align ="center"><input type="submit" value="submit"/></td>


import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class Registration extends HttpServlet
            public void doPost(HttpServletRequest req,HttpServletResponse res) throws
               PrintWriter out = res.getWriter();
               out.println("<CENTER> Reading the Form Values using Servlet</CENTER>");


                 Enumeration en = req.getParameterNames();
                        String name= (String)en.nextElement();
                        out.println(name +"= ");
                        String value = req.getParameter(name);
                        out.println(" ");


SESSION TRACKING : Session tracking is the capability of a server to maintain the current
state of a single client’s sequential requests. The HTTP protocol used by Web servers is
stateless. This means that every transaction is autonomous. This type of stateless transaction is
not a problem unless you need to know the sequence of actions a client has performed while at
your site. Suppose a customer goes to your site to order a movie. The first thing he does is look
at the available titles. When he has found the title he is interested in, he makes his selection. The
problem now is determining who made the selection. Because each one of the client’s requests is
independent of the previous requests, you have no idea who actually made the final selection.

The problem can be solved in two ways :

       The Server sends the client state each time a request to is made as a response.
       The Server stores the client information in file system and send only unique ID (session
         ID) with the response. So, that it can be return back as a request from the client. A user (
         client ) session can be maintained by the following methods as follows.

1) Using hidden form: Using hidden form fields are one of the simplest session-tracking
techniques. Hidden form fields are HTML input types that are not displayed when read by a

<form action=“someaction” method=“post”>
<input type=“hidden” name=“tag1” value=“value1”>
<input type=“hidden” name=“tag2” value=“value2”>
<input type=“submit”>



When you open this HTML document in a browser, the input types marked as hidden will not be
visible. They will, however, be transmitted in the request.

Note: You can see that hidden form fields have their advantages. They are easy to implement
and are supported by most browsers. This technique also has its disadvantages. The hidden fields
must be created in a particular sequence. You are not able to press the Back button on your
browser without losing the additional fields added to the current page. You are also restricted to
dynamically generated documents.

2. The cookie class

           A cookie is small information (Status) that is stored on a client browser by the server.
A cookie can save user name, value, address expiration date and other information so that the
user does not need to enter this data each time. The Cookie contains the HEADER of the HTTP
response that is sent to the client browser using a method addCookie() defined in
HttpServletResponse interface. When a browser receives a cookie, it saves the cookie and
thereafter sends the cookie back to the server each time it accesses a page on that server. Because
a cookie's value can uniquely identify a client, cookies are often used for session tracking. The
Servlet API provides the javax.servlet.http. Cookie class for working with cookies.

Cookie(String name , String value) :This creates a new cookie with an initial name and value.
A servlet can send a cookie to the client by passing a Cookie object to the addCookie( ) method
of HttpServletResponse:

public void HttpServletResponse.addCookie(Cookie cookie) :This method adds the specified
cookie to the response. The code to set a cookie looks like this:
                             Cookie cookie = new Cookie("ID", "123");

A servlet retrieves cookies by calling the getCookies( ) method of HttpServletRequest:


public Cookie[] HttpServletRequest.getCookies():-This method returns an array of Cookie
objects that contains all the cookies sent by the browser as part of the request or an empty array
if no cookies were sent. The code to fetch cookies looks like this:

Cookie [] cookies = req.getCookies();
if (cookies != null)
   for (int i = 0; i < cookies. length; i++)
    String name = cookies[i].getName();
    String value = cookies[i].getValue();

Other Methods includes in Cookie class

String getName ( ): It returns the name of the Cookie.
String getValue ( ) : It returns the Value of the Cookie.
int getMaxAge( ) : It returns the age of the cookie in seconds.
void setMaxAge( ) : It specifies the maximum age of the cookie in seconds.
void setValue( ) : It assigns a new value to the Cookie.
String getDomain( ) : It returns the domain name associated to the Cookie.

Program: a) A HTML page to enter the user name value in the textbox

<title>form control </title>
<body bgcolor="#ffcccc">
<form name="cookieexample" action="feroz/MyCookie">
<table border="1">
 <td><b> Name </b></td>
 <td><input type="text" name="username" value="md feroz" size="20"/></td>
 <td align ="center"><input type="submit" value="submit"/></td>



Program: b) A servlet MyCookie to set the user name as cookie.

public class MyCookie extends GenericServlet
        public void doPost(HttpServletRequest req,HttpServletResponse res) throws
                String user= req.getParameter("username");
                //create cookie
                Cookie c = new Cookie("My_cookie",user);
                //adding cookies to HTTP response
                PrintWriter out = res.getWriter();
                out.println("<h2> My cookie has been set to:"+ user +" </h2>");


Program: c) A servlet getCookie to view the cookie which has been set.

public class getCookie extends GenericServlet
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
               Cookie[] my_cookies = req.getCookies();
               PrintWriter out = res.getWriter();
               out.println("<CENTER><h2> Getting cookies </h2></CENTER><br>");
               for(int i=0;i<=my_cookies.length;i++)
                        String name = my_cookies[i].getName();
                        String value = my_cookies[i].getValue();
                        out.println("Name ="+name);
                        out.println("Value ="+value);



Program: A servlet program that prints the number of times a particular client visited the server
using cookie class

import javax.servlet.*;
import javax.servlet.http.*;
public class VisitClient extends HttpServlet
      public void doGet(HttpServletRequest req, HttpServletResponse res) throws
        ServletException, IOException


            PrintWriter pw = res.getWriter();
            HttpSession session = req.getSession(true);
            Integer count = (Integer) session.getValue(“MD FEROZ”);
              count = new Integer(1);
              count = new Integer(count.intValue()+1);
             cookie.setValue(“MD FEROZ”,count);
             pw.println(“Hit count using Cookie”);
             pw.println(“<H2>You have Visited this page :“ + count+ “times.</H2>”);
             pw.println(“<h2>here your cookie data:</h2>”);
             Cookie c[] = reg.getCookies();
            for(int i=0; i<=c.length; i++)
                    pw.println(“<b>+c[i].getName()+”:::::”+c[i].getValue() +”</b>”);

3) URL Rewriting: If your browser does not support cookies, URL rewriting provides you with
another session tracking alternative. URL rewriting is a method in which the requested URL is
modified to include a session ID. There are several ways to perform URL rewriting.

public class URLRewritingServlet extends HttpServlet
    public void init(ServletConfig config) throws ServletException

 //Process the HTTP Get request
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException
   PrintWriter out = response.getWriter();
   out.println(“<head><title>URL Rewriting</title></head>”);
   // Encode a URL string with the session id appended to it.


    String url = response.encodeRedirectURL(
    // Redirect the client to the new URL
    response.sendRedirect (url);
  //Get Servlet information
  public String getServletInfo() {
    return “URLRewritingServlet Information”;

        This servlet services a GET request and redirects the client to a new URL. This new URL
has the string sid=5748 appended to it. This string represents a session ID. When the servlet that
services the redirection receives the request, it will be able to determine the current user based on
the appended value. At that point, the servlet can perform a database lookup on the user and her
actions based on this ID.

**The advantage of URL rewriting over hidden form fields is the ability to include session-
tracking information without the use of forms. Even with this advantage, it is still a very arduous
coding process.

4) SESSION TRACKING WITH THE SERVLET API: The fourth Technique uses the built-
in HttpSession interface for session tracking. Every user of a site is associated with a
javax.servlet.http.HttpSession object that servlets can use to store or retrieve information about
that user. A servlet uses its request object's getSession( ) method to retrieve the current
HttpSession object.

               public HttpSession HttpServletRequest.getSession(boolean create)

        This method returns the current session associated with the user making the request. If
the user has no current valid session, this method creates one if create is true or returns null if
create is false.
The Method defined in HttpSession interface is as follows.
    1) long getCreationTime() : It returns the time in milliseconds when the session was


   2) String getId() :It returns the session ID
   3) Object getValue(String str) :It returns the object bound in the session under the
      specified name.
   4) void invalidate() :It invalidates the session and removes it from the context.
   5) void putValue(String name,Object obj) :It binds the obj to the name.
   6) boolean isNew() : It returns true if the server creates the session otherwise false.
   7) void removeValue() : This method removes the object bound to the name from the

public class ServletSession extends HttpServlet
  public void doGet(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException
                 PrintWriter out = response.getWriter();
                 out.println("<head><title>Session Tracking </title></head>");
                 out.println("<body bgcolor='#FFC68C'><center>");
                 HttpSession session = request.getSession();
                 int count = (Integer)session.getAttribute("pageCount");
                 out.println("<BR><BR><BR><FONT COLOR='blue' size='18'
                 type='bold'>You Accessed the Page :");
                 out.println("<br><h2>CURRENT DATE : "+new Date().toString());
                 out.println("<br>SESSION ID :"+session.getId());
                 out.println("<br>MAXIMUM INACTIVE INTERVAL
                 out.println("<br><p>CLICK REFRESH TO RELOAD THE PAGE</u></p>");


Disadvantages/problems with servlets technology

With the increasing popularity of Java, servlets took off to become one of the most popular
technologies for Internet development today. But it has some problems as follows.
    Servlet programmers face cumbersome to write servlet code especially when writing
       servlet which consists huge amount of HTML code.
    Servlet code is tedious which consists presentation logic,business logic and request
       processing logic in a single servlet. So, a programmer must have a lot of knowledge in
       java programming and HTML programming to developing a web application using
    Any single modification of servlet HTML code leads to recompile the servlet code and
       reload the server.
    Servlets are not supported by all the web application tools(servers)

SECURITY ISSUES IN SERVLET: Servlets run on the server side, inheriting the security
provided by the Web server. Servlets can also take advantage of the Java Security Manager. Http
protocol provides the built-in authentication based on username/password model, in which the
server maintains the information about the user in database/files. when a user request


aresource,the server responds with a request for the client’s username and password. But the
authentication process is weak because the password is transmitted over the network, anyone can
monitoring the TCP/IP data stream has full access to all the information being
malicious programs can corrupt the database.So,instead of transmitting a password over a
network directly a DIGEST technique is used to protect the password. A servlet can retrieve
information about the server’s authentication using two methods.
                          1.getRemoteUser() and 2.getAuthType().

import javax.servlet.*;
import javax.servlet.http.*;
public class Authentication extends HttpServlet
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws
       PrintWriter out = res.getWriter();
       out.println(“User Name : “ + req.getRemoteUser());
       out.println(“Authentication Type “ + req.getAuthType());


Shared By: