February 26, 2011

Servlets - Overriding init & destroy methods

Override the init() and destroy() methods of a Java Servlet program

package info.icontraining.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InitDemoServlet extends HttpServlet {
 
   public void init() {
      System.out.println("Inside init method");
   }
 
   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      System.out.println("Inside doGet");
   }
 
   public void destroy() {
      System.out.println("Inside destroy method");
   }
}


Adding Servlet configuration in the web.xml

<servlet>
    <servlet-name>initDemoServlet</servlet-name>
    <servlet-class>info.icontraining.servlets.InitDemoServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>initDemoServlet</servlet-name>
    <url-pattern>/initDemo</url-pattern>
</servlet-mapping>


How to test:

1) Open URL: http://localhost:8080/WebAppName/initDemo

2) Check Server console log, it should show "Inside Init method" and "Inside doGet".

3) Refresh browser screen, now server console should show only "Inside doGet". Refresh several more times.

4) Stop the server, search through the server log for "Inside destroy method".

No comments:

Post a Comment