본문 바로가기

Servlet/Servlet Life Cycle

Servlet Life Cycle

Servlet Life Cycle
Servlets are normal Java classes which are created when needed and destroyed when not needed. Since Servlets run within a Servlet Container, creation and destruction of Servlets is the duty of Servlet Container and not yours. Implementing the init() and destory() methods of Servlet interface allows you to be told by the Servlet Container that when it has created an instance of your Servlet and when it has destroyed that instance. An important point to remember is that your Servlet is not created and destroyed for every request it receives, rather it is created and kept in memory where requests are forwarded to it and your Servlet then generates response.

Servlet Initialization
So you have created your Servlet class by extending the HttpServlet class and have placed it in /WEB-INF/classes/ directory of your application. Now when will Servlet Container create an instance of your Servlet? there are two situations :

  • When you have specifically told the Servlet Container to preload your Servlet when the Servlet Container starts by setting the load-on-startup tag to a non-zero value e.g.
    <web-app>
    
      <servlet>
        <servlet-name>test</servlet-name>
        <servlet-class>com.stardeveloper.servlets.TestServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
    
    </web-app>
    So when the Servlet Container starts it will preload your Servlet in the memory.
  • If your Servlet is not already loaded, it's instance will be created as soon as a request is received for it by the Servlet Container.

During the loading of the Servlet into the memory, Servlet Container will call your Servlet's init() method. Since init() is going to be called only once you can put Servlet initialization code in it like getting hold of a database connection or whatever.

Responding to Requests
Once your Servlet is initialized and it's init() method called, any request that the Servlet Container receives will be forwarded to your Servlet's service() method. HttpServlet class breakes this service() method into more useful doGet(), doPost(), doDelete(), doOptions(), doPut() and doTrace() methods depending on the type of HTTP request it receives. So in order to generate respose you should override the doGet() or doPost() method as required.

At this moment all the requests will be forwarded to the appropriate doGet() or doPost() or whatever method as required. No new instance will be created for your Servlet.

사용자 삽입 이미지
사용자 삽입 이미지