Servlet for Beginners

Servlet for Beginners

 

 

 

 

Introduction

 

Web applications are generally based upon Client Server Architecture in which a client sends a request to the server. Depending upon the request, the server responds to the client providing it the required information. To handle such client requests, server side programs are needed. Here comes the need of servlet .A servlet can be defined as a server side program which offers all the advantages of java which includes platform independency also.

 

Example of client request:

 

One of the most common real life scenarios using client server architecture is: web based mail server. When a user enters his userId and password, he is requesting the server to provide him with his mailbox and all other data. Here user doesn’t invoke any program to do all such task but a server side program or set of server side programs do the entire related task. The client request is mapped to a servlet.

 

A user can never invoke the servlet .Servlets are server invoked programs.

 

Java Servlet API 2.3 is defined in java packages: javax.servlet, javax.servlet.http

The package javax.servlet is generic to all protocols i.e. it is protocol independent while javax.servlet.http is specific to http protocol.

 

Some Basic Terminology to have a better understanding of Servlets:

 

Web Container:  A web container provides run time environment for working of web components. The main task of a web container is life cycle management of all the web components. Also it supports creation of objects for the arguments, security related tasks and concurrency control.

 

 

Life Cycle Of A Servlet

 

Controlling the life cycle of a servlet is the task of the container in which servlet is deployed. The life cycle of a servlet has following phases:

 

Initializing a servlet or Birth of a servlet:

 

When a request is first time mapped to a servlet, the container loads the servlet. Then instance of the servlet is created. Then, to instantiate that instance init () is invoked. The Servlet interface provides declaration of init ().To customize this instantiation process, init () method needs to be overridden. If the instantiation can not be completed successfully, UnavailableException should be thrown by such servlet. This method is invoked by any servlet only once in a life time i.e. when it is being loaded first time. The initialization variables, if any, should be placed in this method.

 

Method signature: public void init(ServletConfig config) throws ServletException

 

Providing service for a servlet:

 

After a servlet instance has been instantiated, it should be able to do the needed task i.e. to handle the client side requests. When a servlet is initialized in an appropriate manner, it means an instance of servlet is available. Now each time the server receives request, a new thread is spawned from the same instance and the service () method is invoked. All the application logic is included in this method. It acts as an entry point. The service () method, by default checks the HTTP header of the request to check whether it needs to call doGet () method or doPost () method .In case, both methods need to be invoked, then any of the methods i.e. doPost () and doGet() can call another one.

 

 

Method signature: public void service (ServletRequest request, ServletResponse

                                                     response) throws ServletException, IOException    

                                                                       

 

Destroying/Finalizing a servlet or Death of servlet:

 

A servlet should be destroyed when its task is over. The container invokes destroy () method for a servlet instance when it determines that the services of this servlet are not needed now. Invocation of destroy () method releases all the memory resources being used by the servlet.A servlet should be removed from memory only after all its service methods have been completed. It is the place for all clean up tasks.

 

Method signature: public void destroy ()

 

Discussing the Basic Interfaces and classes in servlet API:

 

1 Servlet interface

2 GenericServlet class

3 HttpServlet class

4 ServletRequest interface

5 ServletResponse interface

6 HttpServletRequset interface

7 HttpServletResponse interface

 

1.  Servlet interface:  This is the interface which a class should implement to become

     a servlet.The following methods must be implemented while implementing

     javax.servlet.Servlet interface:

 

 

è       public void init(ServletConfig config)

è    public void service(ServletRequest request, ServletResponse response)

è    public void destroy()

è    public ServletConfig getServletConfig()

è    public String getServletInfo()

 

 

2.   GenericServlet class: This is the class to provide basic implementation for Servlet

       interface.

 

      public abstract class GenericServlet implements Servlet, ServletConfig,

      Serializable

       

 

       

       It provides following additional methods:

 

 

è       public init()

è       public void log(String message)

è       public void log(String message, Throwable t)

 

 

3.     HttpServlet class: This is a subclass of GenericServlet class.It provides HTTP

      specific implementation of Servlet interface. Mostly the servlet classes

      extend this class to provide functionality of a servlet.

 

            public abstract class HttpServlet extends GenericServlet implements

            Serializable

 

            Here are the mainly used methods as specified in this class:

 

è    service() methods :

 

      There are two variants of service () methods in HttpServlet class as

      discussed below:

 

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

 

 

protected void service (HttpServletRequest request, HttpResponse response) throws ServletException,IOException

 

 

The public service method is implementation of GenericServlet class. Practically the above service methods should not be overridden if only default behavior is needed. In case when additional behavior is required, these methods need to be overridden including the default behavior using super.service().

 

When the container receives a new request, it invokes the methods in following sequence:

 

a)    Firstly, the public service () method is invoked.

 

b)    The arguments are casted to HttpServletRequest and HttpServletResponse respectively and then the public service () method invokes a call to protected service () method.

 

c)    The protected service() method acts as a delegation method to delegate requests to doXXX() methods depending upon the type of HTTP request.

 

è  doXXX() methods:

 

The following protected methods are implemented by HttpServlet class in order to serve different types of client requests:

 

*       protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

 

 

*       protected void doPost(HttpServletRequest request, HttpServletResponse   

response)  throws ServletException,IOException

 

*       protected void doHead(HttpServletRequest request, HttpServletResponse

response) throws ServletException,IOException

 

*       protected void doDelete(HttpServletRequest request, HttpServletResponse

response) throws ServletException,IOException

 

 

*       protected void doOptions(HttpServletRequest request, HttpServletResponse

                                                response) throws ServletException,IOException

 

*       protected void doPut(HttpServletRequest request, HttpServletResponse   

                                     response) throws ServletException, IOException

 

*       protected void doTrace(HttpServletRequest request, HttpServletResponse

response)throws ServletException,IOException

 

 

 

4.     ServletRequest interface:

 

 When the service () method of GenericServlet or the HttpServlet is called, an 

  instance of this object is created by the container.

 

  public interface ServletRequest.

 

  Some of the methods provided by this interface are discussed as below. These

  methods are used to access request parameters from the clients and to         

        manage the request attributes:

 

*       public String getParameter(String name): returns value of the parameter

      corresponding to the key ‘name’. It returns the first value of the list if  

      multiple entries are found corresponding to the same key. And a null value is

      returned if such parameter is not found.

 

*       public String[] getParameterValues(String name) : returns complete list of

      values i.e. returns a String array corresponding to the key ‘name’.

 

*       public Enumeration getParameterNames(): returns name of all parameters in

      the form of Enumeration. An empty enumeration is returned if no request

      parameters are associated with the request being processed.

 

*       public Map getParameterMap() : returns a Map object containing name of

      parameters as keys and set of their corresponding value being the values.

 

*       public Object getAtribute (String name): returns the value of the attribute named as ‘name’. A null is returned if no such attribute exists.

 

*       public Enumeration getAttributeNames(): returns Enumeration object      

      containing names of all attributes.

 

*       public void setAttribute(String name, Object attribute): sets value of attribute

      for a named attribute.

 

*       public void removeAttribute(String name): The named attribute is removed

      from the request. The setting and removal of attributes is useful to maintain

      sessions.

 

5.     ServletResponse interface:

 

  When the service () method of GenericServlet or the HttpServlet is called, an 

  instance of this object is created by the container.

 

   public interface ServletResponse

               

        Some of the important methods provided by this interface are discussed as   

          below:

 

*       public void setContentType(String type) : This method is used to set the

            MIME type for the response. A PrintWriter object is requested to write body 

            data to the response. Before such a request can be made, all response

            headers must be set.

 

*       public java.io.PrintWriter getWriter() throws java.io.Exception: For the same

            HttpServletResponse object, this method should be called only once. This   

            method is used to send character text in response.

 

*       public void resetBuffer(): This is used to reset the underlying buffer i.e. it

            cleans up the underlying buffer by deleting the contents .The status code or

            the response header remains unaffected after invocation of this method.

 

6.        HttpServletRequest  interface :

 

          This interface implements the ServletRequest interface. Hence, all the

          methods of ServletRequest are well available here. It is specific to HTTP

          requests.

 

          Mainly used methods in this interface are the methods which are used to

          access request parameters.

 

    Some other commonly used methods are:

   

 

a)    public String getQueryString() :

b)    public String getHeader(String name)

c)    public String getMethod() : returns type of HTTP request

 

7.        HttpServletResponse interface:

 

         This interface implements the ServletResponse interface. Hence, all the  

         methods of ServletResponse are well available here. It is specific to HTTP

         response.

    

   Some of the methods :

 

a)    public void sendError (int status): This method is used to output various status codes supported by HTTP.

 

b)    public String encodeURL(String url)

 

                             

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

A Simple Servlet

 

/* To import some packages which contain classes which are used by   

     servlet */

 

import javax.servlet.*;

import javax.servlet.http.*;

 

 

/* The servlet ‘SimpleServlet’ extends javax.servlet.http.HttpServlet which              

     is the base class for HTTP servlets */

 

public class SimpleServlet extends HttpServlet

{

 

     /* Overriding doGet() method of HTTPservletRequest */

 

         protected void doGet (HttpServletRequest request, HttpServletResponse

                                        response) throws ServletException, IOException

 

         {

                              /* Setting the content type for output using method of

                                   HttpServletResponse object */

 

                                     response.setContentType(“text/html”);

 

                             /* A PrintWriter object is being requested to write a

                                  response */

 

                                     PrintWriter out= response.getWriter();

 

                             /* Using the PrintWriter object which was obtained in  

                                   Previous step to write response of type text/html */

 

                                     out.println(“<HTML><HEAD><TITLE> A Simple “+

                                                   “Servlet</TITLE></HEAD></BODY></HTML>”);

 

                            /* Closing the PrintWriter object after the response has         

                                 been written */

 

                                     out.close();

         }

}

 

 

 

 

 

 

 

 

 

 

Single Thread Model in Servlets

 

For each servlet name there exists one servlet instance. For all other incoming requests, new threads are spawned from the same instance. That is, service () method might be invoked concurrently by many threads. What if this concurrent execution of service () method is to be avoided?

 

Java Servlet API defines a marker interface named as javax.servlet.SingleThreadModel to provide alternative if the service () method is thread unsafe. This interface is just a marker interface i.e. it does not provide definition of any method but its function is to let the container know that only one thread should be able to execute the service() method at any time.

 

It is suggested to avoid SingleThreadModel .This interface SingleThreadModel is deprecated in servlet API 2.4.

 

There are two approaches that a container may follow in order to ensure that no two threads can concurrently access the service () method. Also combination of both approaches can also be used:

 

v  Request Serialization:

 

              A single instance of the servlet is used for all client requests. Instead of sending multiple requests to that instance at the same time, the requests are sent to the instance in a serialized manner. While one client is being served, all the other

requests will keep waiting for availability of instance.

 

 

v  Instance Pooling:

 

              A pool of servlet instances is maintained by the container. The container picks up an instance from the pool for each new incoming request. The instance is  

returned to the pool after the request has been served.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Distinguishing among different users via concept of session:

 

A session is basically a unique connection between a server and a client to identify that multiple requests are sent by same client i.e. a session enables the server to identify a client across multiple requests.

 

Example:

 

After being login to an email account, the client needs to be identified by the server i.e. The server needs to verify that all the tasks like writing new mail, sending new mail are being done by the same authenticated client.However, the client may be asked to authenticate himself again and again but it is not a practical approach for large business transactions.

 

Other example is of banking transactions.

 

In case of large business transactions, flexibility can be maintained using facilities like:

 

Session:

 

It is required by the server to distinguish among different users. This can be achieved by putting specific request in a specific working session

 

State:

 

State refers to the information associated with the requests. Sometimes the information related to the previous requests is also required to handle a new incoming request.

 

The protocols which maintain the state are known as stateless protocols while stateless is the term used for protocols in which server do not remember any information about previous requests and treat each new request, even from the same client ,as a fresh request. HTTP is a stateless protocol.

 

 

 Maintaining the servlet sessions using Java Servlet API:

 

Java Servlet API provides an interface HttpSession which is used to represent session objects. And HttpServletRequest interface provides methods to create and track session:

 

a)    public HttpSession getSession( boolean create):

 

This method returns the HttpSession object which is associated with the request object representing the request being currently processed. The boolean argument tells the container whether new session is to be created if session does not exist already. If value of ‘create’ is true then a new session is created in case a session does not exist already. However, a null is returned if a session does not exist and  value of ‘create’ is false.

 

 

b)    public HttpSession getSession() :

 

It is similar to the above method with the only difference that it always create a session if one does not exist already.

 

A session consumes memory and other resources. So a session should be closed when not required. For ex: if a user closes his mail application without being logging out, the session is still using resources i.e. session is in inactive state. So it should be closed.

 

The methods provided by HttpSession interface can be grouped as:

 

è  Methods which deal with session lifetime

 

a)    public long getCreationTime() :

 

       This method returns the time of creation of session since January 1, 1970  

        00:00:00 GMT

 

b)    public int getMaxInactiveInterval():

 

        This method returns the time duration in seconds for which session will

        remain active between requests before expiring.

 

c)    public int setMaxInactiveInterval(int interval):

 

It is used to set the time duration in seconds for which session will remain active between requests before expiring .The session is automatically terminated after the specified time interval.

 

d)    public Boolean isNew() :

 

      It returns true or false indicating whether the session is new or not.

 

e)    public void invalidate() :

 

       This method is used to terminate a session. When a user logs out, this

       method is invoked to terminate his session.

 

 

 

è  Methods which associate state with sessions

 

 

a) public Object getAttribute(String name)

b) public Enumeration getAttributeNames(String name)

c) public setAttribute(String name, Object value)

d) public void removeAttribute(String name)

 

 (These methods have been discussed under ServletRequest interface)

 

 

 

 

References :

 

 

 http://www.iam.ubc.ca/guides/javatut99/servlets/lifecycle/index.html

 

 

       http://www.ecerami.com/applied_spring_2004/lectures/life_cycle.ppt

 

 

       http://java.sun.com/j2ee/tutorial/1_3-fcs/index.html

 

 

        http://www.stardeveloper.com/articles/display.html?article=2001062001&page=1

 

 

        

 

 

 

 

Tags: , , , , , , , , , ,

Leave a Reply