Life cycle of servlet in java

Posted by Satyapriyanayak under Others category on | Points: 40 | Views : 935
The javax.servlet.Servlet interface defines the three methods as 
public void init(ServletConfig config)
public void service( ServletRequest req, ServletResponse res)
public void destroy()

When ever a servlet gets called by the first user then the servlet container creates a new instance of the servlet class.The servlet container creates a new thread for each user to call service() method,doGet() method ,doPost() method.All users use common instance of the servlet class.If the service has no user to access it and memory of the servlet container gets full then the instance of the servlet gets destroy and before to it destroy method executes.If servlet container gets closed then all existing instances of the servlet get destroyed and before to it the destroy() method executes.

Can a servlet contain constructor?
A servlet class can contain any type of constructors. The servlet container calls only the default constructor of the servlet class.The parameterized constructor cannot be called by the servlet container but these can be called by the default constructor by using this keyword.


import javax.servlet.*;
import javax.servlet.http.*;
/* Execute this in tomcat 4.1 to get the o/p in console window */
public class lifecycle extends HttpServlet
public lifecycle(int x)
System.out.println("from constructor");
public void init()
System.out.println("Servlet Started Its Execution");
public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException
Thread th=Thread.currentThread();
System.out.println("new user arrived..");
PrintWriter out=res.getWriter();
out.println("<html><body bgcolor='pink'>");
out.println("<h1 align='center'>Yur thread name is : "+th.getName()+"</h1>");
public void destroy()
System.out.println("servlet gets out...");

Comments or Responses

Login to post response