|
| |
A servlet has several special methods which are invoked at different times
during its lifetime:
- When a servlet is first created, its
init method is
invoked. You can override this method to do one-time initialization
for your servlet code.
- Subsequently, each user request results in a thread that calls the
servlet's
service method. Multiple concurrent requests
cause multiple threads to call service simultaneously,
unless the servlet implements the SingleThreadModel
interface. Use of the SingleThreadModel interface
restricts the servlet to a single thread at any given time, which is not
usually encouraged for performance reasons.
The service method implemented in the HttpServlet
class dispatches the HTTP request to:
doGet, for HTTP GET requests
doPost, for HTTP POST requests
doPut, for HTTP PUT requests
doDelete, for HTTP DELETE requests
- Finally, if the server decides to unload a servlet, it first calls the
servlet's
destroy method.
Only a single instance of a given servlet is created, and each incoming user
request for that servlet results in the spawning of a new thread, which then
calls service.
You can override the service method if you wish, but
there are seldom good reasons to do so, and it's discouraged. Overriding doGet,
doPost, etc. is the preferred way to go.
Because of the multi-threaded nature of servlets, it is important to do
appropriate thread synchronization when accessing shared resources -- which
includes class and instance variables! Note that local variables
are not shared resources, and do not have to be synchronized.
|