Java Servlet Life Cycle

The web container maintains Java servlet life cycle as shown below and helps us to initialize, perform action and destroy the servlet instance once it is done.

Below are the Servlet life cycle methods:

init()

This method called once only on servlet initialization on instance creation.

service()

This method will get call every time when request reach to Servlet class.

Usually the service() method doesn’t come into the picture, and most of the time we override servlet class doGet() and doPost() methods.

doGet() → The method sent HTTP GET request and allows us to retrieve data from application web server. Limited amount of data can be send as data get send either as part of URL or header. Get request is limited to a maximum of 2,048 characters, minus the number of characters in the actual path. Get() method is not secure and method mostly use

doPost() → The method sent HTTP POST request allows to send large amount of data to application web server. e.g. submission of any form. Sent data is secure as it is not part of request url.

doPut() → The method sent HTTP PUT request allows to place a file on the server. This can be done with the help of doPost() method too, i personally didn’t see much usage of doPut().

doHead() → The web browser sends a HTTP HEAD request when it wants to see only the headers of a response, such as Content-Type, Content-Length or the resource exist depending on response status code.

doDelete() → This method get call as part of DELETE HTTP request allows to delete a document, webpage or information from the server.

doOptions() → The OPTIONS HTTP request determines which HTTP methods server supports and returns appropriate headers.

doTrace() → HTTP TRACE returns the headers sent with the TRACE request to the client, so that they can be used in debugging.

HttpServletRequest → HttpServletRequest object contains the request that the client or web browser has sent to the servlet.

HttpServletResponse HttpServletResponse object contains the response from the servlet sent to the client.

destroy()

This method called once at the end of the servlet life cycle. This gives us an opportuning to clean up the resources or perform action at the end of the servlet life cycle.

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan