Servlet life cycle defines how a servlet is loaded, instantiated, initialized and handles requests from the clients.
Loading and Instantiating: –
Loading and instantiation can occur when the container is started. When the servlet engine is started, the servlet container loads the servlet class using normal Java class loading facilities. After loading the Servlet class, the container instantiates it
Initialization :-
After the class is Loaded and Instantiated, the servlet engines initalize it by calling the following method:
public void init(ServletConfig config) throws ServletException
In the method init, the config object is an instance of ServletConfig class. The config object contains initialization parameters and a ServletContext instance. The initialization parameters are specific to each servlet and configured in the deployment descriptor as part of the definition of the servlet.
Initialization parameter to the servlet is defined in the deployment descriptor file web.XML like following:
1 2 3 4 5 6 7 8 9 10 |
<servlet> <init-param> <param-name>Emp_id</param-name> <param-value>1</param-value> </init-param> <init-param> <param-name>Emp_name</param-name> <param-value>John</param-value> </init-param> </servlet> |
Processing Request :-
After initialization, the servlet is able to handle client requests.
Destroying :-
The servlet engine stops a servlet by invoking the servlet’s destroy() method. The destroy() method runs only one time during the lifetime of the servlet and this is the end of the servlet.
After a servlet’s destroy() method is invoked, the servlet engine unloads the servlet, and the Java virtual machine eventually performs garbage collection on the memory resources associated with the servlet.
Following three methods are known as servlet life cycle methods.
1) public void init(ServletConfig config) throws ServletException
2) public void doGet(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException
OR
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException
3) public void destroy()
Sau Gambold says
May 29, 2011 at 11:19 pmIt’s really a nice and helpful piece of information. I’m glad that you shared this helpful info with us. Please keep us informed like this. Thanks for sharing.