.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Home >> Articles >> General >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Life cycle of servlet

Posted By:satyapriyanayak       Posted Date: July 24, 2014    Points: 200    Category: General    URL: http://www.dotnetspark.com  

In this article we will know about Life cycle of servlet.

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.*;
import java.io.*;
/* 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...");

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend