Life Cycle of Servlet starts when a servlet application get deployed in the web server. Web container is responsible for calling all the life cycle methods. Servlet has following three life cycle methods :

1. init()
2. service()
3. destroy()

init() method :  init() is the first method to be called in every servlet application. It is a parametrized method with ServletConfig reference as a parameter. When the servelt application is been deployed and run in the web server then a servletConfig object is created by the web container and this is once created at the container start-up only. It must be initialized with ServletConfig parameter mentioned in the web.xml file with the < init-param > tag .
So instance of ServletConfig is created at the container start-up and initialized by calling init() method with the ServletConfig parameter which is mapped in the web.xml file using < init-param > tag.

<init-param > tag has sub-tags < param-name > and < paran-value > .

< param-name > is a logical on basic of which value can be retrieved by hard-coding the name as a string in the following method.

getInitParameter(String paramName)
< param-value >  SevletConfig instance get initialized with the value mentioned in this tag. 

Why we are configuring < init-param > tag in web.xml ?

It is because SerlectConfig object is created once at the container start-up so value must be passed in the web.xml file so it must be read and initialized to the ServletConfig object at the container start-up.

Syntax of init() method :

 public abstract void init(ServletConfig sc)  throws ServletException 

It is the abstract method declared in servlet interface and overridden in GnericServlet class which implements servlet interface and finally GenericServlet class is extended  by HttpServlet class which we are extending with our java class.

Note: We must not override because it is internally called by the container to initialize the ServletConfig instance with the ServelConfig parameters.

service() method : service() method is the method we override in the our servlet class to get the control of HttpServletRequest and HttpServletResponse to handle the request from client and processed to get ready the response and store the required information in the HttpServletResponse object to get displayed in the JSP page.
So we need to override to have our own implementation of processing the client request by connecting with database. It may be retrieving ,storing or editing to the database.

Syntax of service() method :
protected void service(HttpServletRequest req, HttpServletResponse resp)                                                                       throws ServletException, IOException

This is the method we are overriding from HttpServlet class.


1 comment:

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic