The Servlet Life Cycle

By: aathishankaran Emailed: 1700 times Printed: 2205 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

You might know that only a single instance of a servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. I’ll now be more specific about how servlets are created and destroyed, and how and when the various methods are invoked. I’ll give a quick summary here, then elaborate in the following subsections. 

When the servlet is first created, its init method is invoked, so that is where you put one-time setup code. After this, each user request results in a thread that calls the service method of the previously created instance. Multiple concurrent requests normally result in multiple threads calling service simultaneously, although your servlet can implement a special interface that stipulates that only a single thread is permitted to run at any one time. The service method then calls doGet, doPost, or another doXxx method, depending on the type of HTTP request it received. Finally, when the server decides to unload a servlet, it first calls the servlet’s destroy method. 

ServletUtilities.java 

package coreservlets; 
import javax.servlet.*; 
import javax.servlet.http.*; 
public class ServletUtilities { 
public static final String DOCTYPE = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">"; 
public static String headWithTitle(String title) { 
return(DOCTYPE + "\n" + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n"); 

... 


The init Method 

The init method is called when the servlet is first created and is 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 can be created when a user first invokes a URL corresponding to the servlet or when the server is first started, depending on how you have registered the servlet with the Web server. It will be created for the first user request if it is not explicitly registered but is instead just placed in one of the standard server directories. See the discussion of Section 2.2 (A Simple Servlet Generating Plain Text) for details on these directories. 

The service Method 

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., as appropriate. Now, if you have a servlet that needs to handle both POST and GET requests identically, you may be tempted to override service directly as below, rather than implementing both doGet and doPost. 

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

This is not a good idea. Instead, just have doPost call doGet (or vice versa), as below. 

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

// Servlet Code 



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

doGet(request, response); 



Although this approach takes a couple of extra lines of code, it has five advantages over directly overriding service: 

  1. You can add support for other services later by adding doPut, doTrace, etc., perhaps in a subclass. Overriding service directly precludes this possibility. 
  2. You can add support for modification dates by adding a get-LastModified method. If you use doGet, the standard service method uses the getLastModified method to set Last-Modified headers and to respond properly to conditional GET requests (those containing an If-Modified-Since header). 
  3. You get automatic support for HEAD requests. The system just returns whatever headers and status codes doGet sets, but omits the page body. HEAD is a useful request method for custom HTTP clients. For example, link validators that check a page for dead hypertext links often use HEAD instead of GET in order to reduce server load. 
  4. You get automatic support for OPTIONS requests. If a doGet method exists, the standard service method answers OPTIONS requests by returning an Allow header indicating that GET, HEAD, OPTIONS, and TRACE are supported. 
  5. You get automatic support for TRACE requests. TRACE is a request method used for client debugging: it just returns the HTTP request headers back to the client. 

The destroy Method 

The server may decide to remove a previously loaded servlet instance, perhaps because it is explicitly asked to do so by the server administrator, or perhaps because the servlet is idle for a long time. Before it does, however, it calls the servlet’s destroy method. 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. Be aware, however, that it is possible for the Web server to crash. After all, not all Web servers are written in reliable programming languages like Java; some are written in languages (such as ones named after letters of the alphabet) where it is easy to read or write off the ends of arrays, make illegal typecasts, or have dangling pointers due to memory reclamation errors. Besides, even Java technology won’t prevent someone from tripping over the power cable running to the computer. So, don’t count on destroy as the only mechanism for saving state to disk. Activities like hit counting or accumulating lists of cookie values that indicate special access should also proactively write their state to disk periodically.


JSP Home | All JSP Tutorials | Latest JSP Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(2)


1. View Comment

thanks happy to see such a site about java!

View Tutorial          By: nnnmore at 2007-03-16 06:29:20
2. View Comment

Very well explained and perfectly summarised.

View Tutorial          By: Sachin at 2009-08-30 12:39:27

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by aathishankaran
Web Security Issues
The Web User's Perspective
Server-side plug-Ins
The best way to avoid security vulnerabilities with new server
JavaScript Security
Window Object
Working with Status Bar Messages
Retrieving a Portion of a String
Referencing Windows
Math Object
Frame Object
Document Object
Closing Windows
Built-in Object in Javascript
Textarea Object

More Tutorials in JSP
LifecycleException: service.getName(): "Catalina"; Protocol handler start failed: `java.net.BindException: Permission denied <null>:80
JSP Alert Example
JSP CheckBox Example
Uploading an Image to a Database using JSP
Uploading a file to a server using JSP
A JSP page that gets properties from a bean
The page Directive in JSP
The taglib, tag, include, attribute and the variable Directive in JSP
Declarations in JSP
Scriptlets and Expressions in JSP
Tag Libraries in JSP
The Request Object in JSP
The Response Object in JSP
The Out Object in JSP
The Session Object in JSP

More Latest News
Most Viewed Articles (in JSP )
JSP Example to connect to MS SQL database and retrieve records
What are the different scopes in JSP?
JSP Program for display Date
JSP CheckBox Example
Embedding java codes in jsp sciptlets
Declaring variable in JSP
HttpClient
The Advantages of JSP
The Servlet Life Cycle
Referencing Windows
Deploying an Individual JSP on Tomcat
Getting HTTP Request Headers in a JSP
Getting Started with JSP
The taglib, tag, include, attribute and the variable Directive in JSP
Declarations in JSP
Most Emailed Articles (in JSP)
What is JSP?
JSP pages in servlet
Declaring variable in JSP
A Servlet That Generates HTML
Simple HTML-Building Utilities
Checkbox Object
Retrieving a Portion of a String
JSP Example to connect to MS SQL database using Tomcat Connection Pool
The Application Object in JSP
Cookies using JSP or Java Bean
Click to Activate and Use this control
The JSP Program running first Time.
Scriptlets
Server Side Programming
Syntax For JSP Declaratives