Servlet LifeCycle

SHARE & COMMENT :

Servlets are small programs that run at server side and creates dynamic web pages. Servlets respond to any type of requests sent by user. In MVC architecture servlet act as controller. The controller is the logic that processes and responds to the user requests. Life Cycle of Servlets contain following steps:

  • Load servlet class.
  • Create servlet instance.
  • Call the init method.
  • Call the service method.
  • Call the destroy method.

Servlet Class Loading

The first step in creation of a servlet component is to load the servlet class file into web container’s JVM (Java Virtual Machine). This step is invoked when either first time servlet is invoked or configured in the web.xml with load-on-startup element.

Creating Servlet Instance

After the servlet class has been loaded into the web container’s JVM, the next step is to create an instance of that class. Servlet specification declares one and only one servlet instance will be created for a single definition in the deployment descriptor.

The init () method

After servlet instance is created, the web container initializes the parameters that were specified in the deployment descriptor. This method is invoked only when servlet is first loaded into memory. The syntax of init () method look like this:

public void init () throws Servlet Exception {
//code
}

The service () method

After the servlet component has been initialized, the web container can begin sending requests to that component using the service method .This method is used to process the request. For each request the web container will issue unique request and response to the service method. The syntax of service () method as follows:

public void service (Servletrequest request, Servletresponse  response)
     throws ServletException, IOException {
}

When service () method is called by web container it invokes doGet (), doPost (), doPut (), doDelete (), doTrace (), doOptions (), getLastModified () methods.

The doGet () and doPost () are the two methods which are frequently used with each service request. We must override doGet () and doPost () methods depending on type of request.

The doGet () method: By using doGet () method we can send specific amount of data. If we use doGet () method data is shown in address bar. We must override doGet () method depending on type of request. It can be defined as follows:

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

The doPost () method: We can send large amount of data by using doPost () method. By using this method data is not viewable in address bar. When we want to send secure data like passwords and other things doPost () method is used. We must override doPost () method depending on type of request. It can be defined as follows:

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

doDelete (): It is used to delete files, web pages or documents from the server. If requests are formatted incorrectly then it will return HTTP “Bad Request” error. It can be defined as follows:

 protected  void doDelete (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
 //code
}

doPut() : This method is used to put files, web pages or documents in the server means for uploading files on the server. If requests are formatted incorrectly then it will return HTTP “Bad Request” error. It can be defined as follows:

protected  void doPut (HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException{
  //code
}
 

doTrace () : This method is used for logging and debugging purpose. It can be used for testing the requested message. There is no need to override this method. It can be defined as follows:

protected void doTrace(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException{
  //code
 }
             

doOptions (): This method handles OPTIONS request. There is no need to override this method. It determines which HTTP method supported by server and returns correct header. If requests are formatted incorrectly then it will return HTTP “Bad Request” error.
It can be defined as follows:

protected void doOptions(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
 //code
 }

getLastModified (): It returns the time when request was last modified. This method should override GET request to return modification time of object.
It can be defined as follows:

protected long getLastModified (HttpServletRequest request)
     throws ServletException, IOException{
                     //code
}  

The destroy () method

When a web application is being shut down web container will call destroy method. It is used to clean up any resources that servlet might have initialized. The syntax of destroy () method as follows:

public  void destroy(){
//code
}

Servlet LifeCycle Example

Let’s create a servlet example using Eclipse IDE. To create servlet application we need to use following steps:

    • Environment used:
      • JDK
      • Eclipse IDE
      • Apache Tomcat Server
      • Java-api
    • Open the Eclipse IDE and Go to File Menu ->New->Select Dynamic Web Project.
      servlet_lifecycle1_demo
    • Enter Project Name click on Next.
    • Click on Generate web.xml deployment descriptor and click Finish.
    • Now under the project, click on Java Resources ->select src, right mouse click and select New->Package and type the name as javabeat.net.servlets
      servlet_lifecycle2_demo
    • Now click on the package javabeat.net.servlets and New ->select Servlet
      servlet_lifecycle3_demo
      Type the class name as ServletDemo and click Finish.
    • Now to add servlet-api jar to project we need to do following steps.
      • Right mouse click on Project name, select -> Properties ->select Java Build Path->Click on Add External JAR’s.
      • Select servlet-api.jar from Apache Tomcat directory.
      • Click on Open and click OK.

      servlet_lifecycle4_demo

    • Add the following content to the ServletDemo.java:
      package javabeat.net.servlets;
      
      import java.io.IOException;
      import java.io.PrintWriter;
      
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      
      /**
       * Servlet implementation class ServletDemo
       */
      public class ServletDemo extends HttpServlet {
      
      /**
       * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
       */
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      	response.setContentType("text/html");
      	PrintWriter out = response.getWriter();
      
      	out.println("<html>");
      	out.println("  <head>");
      	out.println("    <title>SimpleServlet</title>");
      	out.println("  </head>");
      	out.println("  <body>");
      	out.println("    Hello, World");
      	out.println("  </body>");
      	out.println("</html>");
      	}
      
      }
      
    • Edit the web.xml and include the following content to it:
      <?xml version="1.0" encoding="UTF-8"?>
      <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
        <servlet>
              <servlet-name>ServletDemo</servlet-name>
              <servlet-class>javabeat.net.servlets.ServletDemo</servlet-class>
          </servlet>
      
          <servlet-mapping>
              <servlet-name>ServletDemo</servlet-name>
              <url-pattern>/ServletDemo</url-pattern>
          </servlet-mapping>
      </web-app>
      
    • Select the class ServletDemo right mouse click->Run As and select Run on Server, an output as shown below should be achieved:

servlet_lifecycle5_demo

Previous Tutorial : Servlet API  || Next Tutorial : Generic Servlet and HTTP Servlet

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better