Servlet life cycle:

There is a simple life cycle, which is followed by each servlet.
When the web server starts the web container looks for the deployed webapps and then starts searching for the servlet class files. So finding the class is the first step. Loading the class and creating Servlet instance is the second step it happens either on container start up or first client request(container gives you choice. you can use to start autometically).
Then it calls the init() method(In javax.servlet.Servlet interface). As soon as the container loads a servlet it invokes the init() method prior to servicing any requests. It always completes before the first call to service() method. The init() runs only once in whole servlet’s life at this time. Again it is not called again for each user request. You can use init() method to put the one time code like create I/O intensive resources, such as database connections, for use across multiple invocations.
Syntax:
public void init()throws ServletException{
ServletConfig config=getServletConfig();
String param1=config.getInitParameter(“param1”);}

The service phase is the second phase of servlet life cycle. In this phase service() method is called. From second request unwords the request come to this phase without going through initialization phase. The service() method is invoked once per request. This phase solely responsible for generating response to the respective requests. This method takes two parameters javax.servlet.ServletRequest and javax.servlet.ServletResponse. When there is a client request to the server then the container creates two instances of these objects. These two instances are different for each different requests. Servlet is single instance and multi threaded model. That means only one instance of Servlet is loaded into the container at a given time. Initialization phase is done only once and after that each request is handled concurrently by threads executing the service() method. The server spawns this new thread may be by rescuing an idal thread from the thread pool. If it is HttpServlet it checks the HTTP request type (GET,POST,PUT,DELETE,etc) and calls doXXX() as appropriate.
Syntax:
Public void doGet(HttpservletRequest request,HttpServletResponse response) throws ServletException,IOException{}

The destruction phase is the final phase of servlet life cycle. In this case the Servlet interface defines the destroy() method. When time comes that the servlet is about to be removed then the container calls the destroy() method. The codes to free the resources(clean up codes like closing data base connections) should go inside this method. The server administrator explicitely does it.

No comments:

Post a Comment