If I enable automatic servlet reloading for a webapp, will the init() method of the servlet get executed for each automatic reload?

Avi Kak


This question is important because it is possible to misconstrue the community literature dealing with servlets and believe that the init() method of a servlet will get executed only once -- the first time a servlet gets loaded into the container.

The following simple servlet, called TestServlet, can be used to verify the answer to the question. In my Tomcat 3.1 container, this servlet is inside a webapp called test-suite and resides in the directory


In accordance with the jGuru FAQ posting, I have enabled automatic reloading for this webapp by including the following element in the server.xml file in the TOMCAT_HOME/conf directory:

<Context path="/test-suite" docBase="webapps/test-suite" debug="0" reloadable="true" > </Context>

As the following code shows, the servlet contains a line "Revision number: xx" where xx can be edited to create a change in the servlet to trigger automatic reload. Upon each reload, the print statement in the init() method will be printed out in the Tomcat console window. Here is the code for this servlet:

//filename: TestServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TestServlet extends HttpServlet {

  public void init() throws ServletException 
    System.out.println("TestServlet being loaded into the container");

  public void doGet(HttpServletRequest request, HttpServletResponse response)
                     throws ServletException, IOException
    response.setContentType( "text/html" );
    PrintWriter out = response.getWriter();

    out.println( "<html>" +  
                      "<head><title> TestServlet </title></head>" +
                      "Hello there from TestServlet  ----- " +
                      "Revision number: 18" +
                      "</body></html>" );

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact