|
Answer» A Java servlet is typically multithreaded. This MEANS that multiple requests can be sent to the same servlet and they can be executed at the same TIME. All the local variables (not pointing to shared resources) INSIDE the servlet are automatically thread-safe and are request specific. Care has to be taken when the servlet is accessing or modifying the global shared variable. The servlet instance lifecycle for different requests are managed by the web container as follows: - User clicks on a link in a client that requests a response from a server. In this instance, consider that the client performs GET request to the server as shown in the image below:
- The web container intercepts the request and identifies which servlet has to serve the request by using the deployment descriptor file and then creates two objects as shown below-
- HttpServletRequest - to send servlet request
- HttpServletResponse - to get the servlet response
- The web container then creates and allocates a thread that inturn creates a request that calls the SERVICE() lifecycle method of the servlet and passes the request and response objects as parameters as shown below:
- service() method decides which servlet method - doGet() or doPost() or doPut() or doDelete()- depending on the HTTP requests received from the client. In our case, we got the GET request from the client and hence the servlet will call the doGet() method as described below.
- Servlet makes use of the response object obtained from the servlet method for writing the response to the client.
- Once the request is served completely, the thread DIES and the objects are made ready for garbage collection.
|