1. Overview
In this tutorial, we’ll understand conceptually what servlets and servlet containers are and how they work.
We’ll also see them in the context of a request, response, session objects, shared variables, and multithreading.
2. What Are Servlets and Their Containers
Servlets are a component of the JEE framework used for web development. They are basically Java programs that run inside the boundaries of a container. On the whole, they are responsible for accepting a request, processing it, and sending a response back. Introduction to Java servlets provides a good basic understanding of the subject.
To use them, servlets need to be registered first so that a container, either JEE or Spring-based, can pick them up at start-up. In the beginning, the container instantiates a servlet by calling its init() method.
Once its initialization is complete, the servlet is ready to accept incoming requests. Subsequently, the container directs these requests for processing in the servlet’s service() method. After that, it further delegates the request to the appropriate method such as doGet() or doPost() based on the HTTP request type.
With destroy(), the container tears the servlet down, and it can no longer accept incoming requests. We call this cycle of init-service-destroy the lifecycle of a servlet.
Now let’s look at this from the point of view of a container, such as Apache Tomcat or Jetty. At start-up, it creates an object of ServletContext. The job of the ServletContext is to function as the server or container’s memory and remember all the servlets, filters, and listeners associated with the web application, as described in its web.xml or equivalent annotations. Until we stop or terminate the container, ServletContext stays with it.
However, the servlet’s load-on-startup parameter plays an important role here. If this parameter has a value greater than zero, only then the server initializes it at start-up. If this parameter is not specified, then the servlet’s init() is called when a request hits it for the very first time.
3. Request, Response, and Session
In the previous section, we talked about sending requests and receiving responses, which basically is the cornerstone of any client-server application. Now, let’s look at them in detail with respect to servlets.
In this case, a request would be represented by HttpServletRequest and response with HttpServletResponse.
Whenever a client such as a browser, or a curl command, sends in a request, the container creates a new HttpServletRequest and HttpServletResponse object. It then passes on these new objects to the servlet’s service method. Based on the HttpServletRequest‘s method attribute, this method determines which of the doXXX methods should be called.
Apart from the information about the method, the request object also carries other information such as headers, parameters, and body. Similarly, the HttpServletResponse object also carries headers, parameters, and body – we can set them up in our servlet’s doXXX method.
These objects are short-lived. When the client gets the response back, the server marks the request and response objects for garbage collection.
How would we then maintain a state between subsequent client requests or connections? HttpSession is the answer to this riddle.
This basically binds objects to a user session, so that information pertaining to a particular user can be persisted across multiple requests. This is generally achieved using the concept of cookies, using JSESSIONID as a unique identifier for a given session. We can specify the timeout for the session in web.xml:
<session-config>
<session-timeout>10</session-timeout>
</session-config>
This means if our session has been idle for 10 minutes, the server will discard it. Any subsequent request would create a new session.
4. How Do Servlets Share Data
There’re various ways in which servlets can share data, based on the required scope.
As we saw in the earlier sections, different objects have different lifetimes. HttpServletRequest and HttpServletResponse objects only live between one servlet call. HttpSession lives as long as it’s active and hasn’t timed out.
ServletContext‘s lifespan is the longest. It’s born with the web application and gets destroyed only when the application itself shuts down. Since servlet, filter, and listener instances are tied to the context, they also live as long as the web application is up and running.
Consequently, if our requirement is to share data between all servlets, let’s say if we want to count the number of visitors to our site, then we should put the variable in the ServletContext. If we need to share data within a session, then we’d save it in the session scope. A user’s name would be an example in this case.
Lastly, there’s the request scope pertaining to data for a single request, such as the request payload.
5. Handling Multithreading
Multiple HttpServletRequest objects share servlets among each other such that each request operates with its own thread of the servlet instance.
What that effectively means in terms of thread-safety is that we should not assign a request or session scoped data as an instance variable of the servlet.
For example, let’s consider this snippet:
public class ExampleThree extends HttpServlet {
private String instanceMessage;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String message = request.getParameter("message");
instanceMessage = request.getParameter("message");
request.setAttribute("text", message);
request.setAttribute("unsafeText", instanceMessage);
request.getRequestDispatcher("/jsp/ExampleThree.jsp").forward(request, response);
}
}
In this case, all requests in the session share instanceMessage, whereas message is unique to a given request object. Consequently, in the case of concurrent requests, the data in instanceMessage could be inconsistent.
6. Conclusion
In this tutorial, we looked at some concepts around servlets, their containers, and a few essential objects they revolve around. We also saw how servlets share data and how multi-threading affects them.
As always, source code is available over on GitHub.