1. An overview of the

In this short article,What are we going to conceptually understandservletservletContainers and how do they work. They can also be seen in the context of requests, responses, session objects, shared variables, and multithreading.

2. Servlets and their containers

Servlets are a common JEE component for Web development. They are basically Java programs that run inside container boundaries. In general, they are responsible for receiving requests, processing requests, and returning responses.

To use them, you first need the container to register servlets, and either jee-based or Spring-based containers can receive them at startup. At the beginning, the container instantiates the servlet by calling the init() method. After initialization, the servlet is ready to accept incoming requests. The container then directs these requests to the servlet’s Service method for processing. It then delegates the request further to the appropriate method, such as doGet() or doPost(), based on the HTTP request type.

With destroy(), the container destroys the servlet and no longer accepts incoming requests. We refer to this init-service-destroy cycle as the life cycle of the servlet.

Now from a container perspective, for example Apache Tomcat or Jetty at startup creates an object called a ServletContext, and the ServletContext’s job is to act as memory for the server or container, And remember all the servlets, filters, and listeners associated with your Web application, such as its web.xml file or equivalent annotations. The ServletContext retains it until the container is stopped.

Anyway,servlettheload-on-startupMetrics play an important role. If the value of this parameter is greater than zero, the server initializes it only at startup. If this parameter is not specified, the request is hit for the first timeservletWhen it is calledinit().

3. Request, Response and Session

In the previous section, we discussed sending requests and receiving responses, which are basically the foundation of any CS application. Now let’s take a closer look at them from the perspective of servlets.

In this case, the request will be represented by HttpServletRequest and the response will be represented by HttpServletResponse.

Each time a browser or curl command sends a request, the container creates a new HttpServletRequest and HttpServletResponse object. These new objects are then passed to the servlet’s Service method. Based on the Method attribute of HttpServletRequest, this method determines which doXXX method should be invoked.

In addition to information about methods, the Request object carries other information, such as headers, parameters, and bodies. Similarly, the HttpServletResponse object also carries headers, parameters, and bodies — we can set them in the servlet’s doXXX method.

The lives of these objects are fleeting. When the client gets the response, the server marks the request and response objects for garbage collection. So how do we maintain a state between subsequent client requests or connections? The answer is HttpSession.

The idea is to bind these objects to user sessions so that information relevant to a particular user can be persisted across multiple requests. This is usually done by using the concept of cookies, using [JSESSIONID] as the unique identifier for a given session. We can specify the session timeout in web.xml.

<session-config>
    <session-timeout>10</session-timeout>
</session-config>
Copy the code

The above configuration means that if the session is idle for 10 minutes, the server will discard it. Any subsequent requests will create a new session.

4. Servlets share data

Servlets can share data in a number of ways, depending on the desired scope.

As mentioned in the previous section, different objects have different life cycles. The HttpServletRequest and HttpServletResponse objects exist only between a servlet call. HttpSession persists as long as it is active and has not timed out.

The ServletContext has the longest lifetime. It is born with the Web application and is destroyed only when the application itself is closed. Because servlet, Filter, and Listener instances are bound to context, they also exist as long as the Web application is up and running.

Therefore, if our requirement is to share data among all servlets, let’s say we want to count visitors to our site, then we should put variables in the ServletContext. If we need to share data in a session, then we keep it in session scope. In this case, the user name is an example.

Finally, there is the request scope associated with the data of a single request, such as the request payload.

5. Handle multithreading

Multiple HttpServletRequest objects share servlets with each other so that each request is operated on using its own servlet instance thread.

In terms of thread safety, this essentially says: we should not specify request – or session-scoped data as instance variables of servlets.

For example, the following code 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); }}Copy the code

In this case, all requests in the session share instanceMessage, and Message is unique to a given request object. Therefore, in the case of concurrent requests, the data in instanceMessage may be inconsistent.

6. Summary

In this tutorial, we explored some of the concepts of servlets, their containers, and some of the basic objects around them, as well as how servlets share data and how multithreading affects them.