Java Servlet Life Cycle in detail
The web container maintains below Servlet class life cycle 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 the client has made of the servlet.
- response — an HttpServletResponse object that contains the response the servlet sends 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.
I hope you found out this article interesting and informative. Please share it with your friends to spread the knowledge.
You can follow me for upcoming blogs follow.
Thank you!