javax.servlet.Servlet interface

Introduction 

The javax.servlet.Servlet interface defines the three methods as
  1. public void init(ServletConfig config)   
  2. public void service( ServletRequest req, ServletResponse res)   
  3. public void destroy()   
Whenever 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 a 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.
 
Program
  1. import javax.servlet.*;  
  2.  import javax.servlet.http.*;  
  3.  import java.io.*;  
  4.  /* Execute this in tomcat 4.1 to get the o/p in console window */  
  5.  public class lifecycle extends HttpServlet  
  6.      {  
  7.          public lifecycle(int x)  
  8.          {  
  9.              System.out.println("from constructor");  
  10.          }  
  11.          public void init()  
  12.          {  
  13.              System.out.println("Servlet Started Its Execution");  
  14.          }  
  15.          public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException  
  16.          {  
  17.              res.setContentType("text/html");  
  18.              Thread th=Thread.currentThread();  
  19.              System.out.println("new user arrived..");  
  20.              PrintWriter out=res.getWriter();  
  21.              out.println("<html><body bgcolor='pink'>");  
  22.              out.println("<h1 align='center'>Yur thread name is : "+th.getName()+"</h1>");  
  23.              out.println("</body></html>");  
  24.          }  
  25.          public void destroy()  
  26.          {  
  27.              System.out.println("servlet gets out...");  
  28.          }  
  29.      }