Servlet Lifecycle Overview
The life cycle of a servlet can be categorized into four parts:
- Loading and Instantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the
<load-on-startup>
attribute in theweb.xml
file. If<load-on-startup>
has a positive value, the servlet is loaded with the container; otherwise, it loads when the first request is made. After loading, the container creates instances of the servlet. - Initialization: After creating the instances, the servlet container calls the
init()
method and passes the servlet initialization parameters to it. Theinit()
method must be called before the servlet can service any requests. Initialization parameters persist until the servlet is destroyed. Theinit()
method is called only once throughout the servlet's life cycle. If the servlet is successfully loaded, it will be available for service; otherwise, the servlet container will unload it. - Servicing the Request: After successful initialization, the servlet is available for service. The servlet creates separate threads for each request. The servlet container calls the
service()
method to handle requests. This method determines the request type and calls the appropriate method (doGet()
ordoPost()
) to handle the request and send a response using the response object's methods. - Destroying the Servlet: If the servlet is no longer needed, the servlet container calls the
destroy()
method. Likeinit()
, this method is called only once throughout the servlet's life cycle. Thedestroy()
method indicates that the servlet should no longer service requests, and it releases all associated resources. The Java Virtual Machine then claims the memory for garbage collection.
Comments
Post a Comment