Know the Servlet Life Cycle
by, 11-28-2011 at 07:04 PM (1303 Views)
If you are programming in java on the back end, one of the key enabling technologies that you must know is servlets. Basically a servlet is a class that handles HTTP responses and makes HTTP Requests. Iím going to assume that you know enough about servlets to be able to override doGet and doPost in order to do some useful work (generate HTML) with your servlets, but what you might not know is the servlet lifecycle. I outline this below in order to improve your understanding how servlets work and how you can use them.
Init - The first method called when the servlet is created is the init method. It is never called again even after a user request. There are two versions of it, one that takes no argument and another that takes a ServletConfig object as an argument. Use the version that takes an argument when you need to read server specific settings before your servlet can complete initialization.
Service - When a server receives a request for a servlet, the server creates a new thread and then calls service. The service method checks the HTTP request type (GET,POST, PUT, DELETE, OPTIONS, TRACE, etc) and calls the appropriate method (i.e. doGet, doPost, doPut, doDelete, doOptions, doTrace, etc). You can override these functions in order to do more processing of the request.
doGet, doPost and the other doXXX - These are the methods that you use to override the default processing in order to do extra processing of the request. Please remember that there is no doHead method because the system uses the header and status line settings of doGet to respond to HEAD requests.
destroy - The servlets destroy method is called when you configure the servlet to remove its previously loaded servlet instance or when you configure it to be removed because it has been idle for an extended period of time. This method is use to clean up its use of resources like database connections, threads, cookies, etc.
Finally one thing have have not mentioned is the use of the SingleThreadModel interface in order to guarantee that the system will never create more than one request thread for accessing a single instance of the servlet. In this situation, requests are queued and passed one request at a time to the servletís single instance or to a pool of multiple instances handling the request one at a time. Normally, the system will make a single instance of your servlet and then create a new thread for each user request. This means that often there will be multiple simultaneous threads running each handling their own user request.