Programming Tutorials

The Servlet Life Cycle

By: aathishankaran in JSP Tutorials on 2007-02-14  

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.  

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.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in JSP )

Latest Articles (in JSP)