The servlet lifecycle

Before we go on, a few words about the lifecycle of servlets is in order. There are three methods implement the lifecycle of a servlet: init(), service(), and destroy(). Prior to handling client requests, the servlet is instantiated and initialized by the servlet container (Tomcat in our case). Only one instance of each servlet is instantiated by the servlet container. During this initialization phase, the container calls init() to give the servlet a chance to run initialization code. Servlets operate in a multithreaded fashion, which means that their methods may be invoked by a number of threads. Upon receiving the first client request, the container starts a new thread or allocates one from the pool. Then, the execution of the servlet is assigned to that thread, which carries on by invoking the servlet's service() method.

Tip

It is worth emphasizing that init() is executed only once. Also the container is not able to invoke service() before init() completes.

service() takes two parameters: a request object (which is an instance of javax.servlet.http.HttpServletRequest) and a response object (which is an instance of javax.servlet.http.HttpServletResponse). It is through these two instances that the container accesses the client request and generates output. Within service(), the request object is examined to determine what sort of request it is. After determining the request type, service() dispatches the request and response objects to the HTTP-related method responsible for implementing the request in question. Two examples of HTTP-related methods are doGet() and doPost(). These methods correspond to the HTTP GET and POST operations, respectively.

Tip

In addition to doGet() and doPost(), which are used most of the time, HttpServlet also contains the doPut() and doDelete() methods. These methods correspond to the HTTP PUT and DELETE operations, respectively. But since these two are seldom used, we will not go into detail. It suffices you to know that they exist.

Lastly, the main purpose of destroy() is to give servlets a chance to clean things up. Summing up, most of the time when implementing your own servlets, the three methods that you will have to override are init, doGet, and doPost (and possibly destroy if you need to clean some resources up).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset