Saturday, May 21, 2011

Servlet Life Cycle

A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.

The methods which are used to initialize a servlet, to service requests, and to remove a servlet from the server are called servlet life cycle methods. These are three methods namely init(), service(), destroy().

Init(): The servlet container calls the init method exactly once after instantiating the servlet. The init method must complete successfully before the servlet can receive any requests
It Contains all information code for servlet and is invoked when the servlet is first loaded.
You can override this method to write initialization code that needs to run only once, such as loading a driver, initializing values and soon, another case you can leave normally blank.

public void init(ServletConfig config)throws ServletException

Service() : is called by the Servlet container after the init method to allow the servlet to respond to a request. Service method receives the request from the client and identifies the type of request and delegates them to doGet() or doPost() for processing.

public void service(ServletRequest request,ServletResponce response) throws ServletException,  IOException

Destroy() : The Servlet Container calls the destroy( ) before removing a Servlet Instance from Sevice. Executes only once when the Servlet is removed from Server.

public void destroy() 

Click here to know about Servlets

No comments: