How HttpServletRequest works

Learn how httpservletrequest works with practical examples, diagrams, and best practices. Covers servlets development techniques with visual explanations.

Understanding HttpServletRequest: The Gateway to Servlet Interaction

Hero image for How HttpServletRequest works

Explore the fundamental role of HttpServletRequest in Java Servlets, how it captures client data, and its key methods for accessing request information.

In the world of Java Servlets, HttpServletRequest is a cornerstone. It's the primary object that encapsulates all the information sent by a client (like a web browser) to the server. When a client makes a request, the web container (e.g., Tomcat, Jetty) parses the raw HTTP request and populates an HttpServletRequest object with all the details. This object is then passed to the appropriate servlet's doGet(), doPost(), or other doXxx() methods, allowing your application to interact with the client's input.

The Lifecycle of an HTTP Request in a Servlet

Understanding how HttpServletRequest fits into the overall request-response cycle is crucial. When a client sends an HTTP request, it travels over the network to the web server. The web server then forwards this request to the servlet container. The container creates an HttpServletRequest object (and an HttpServletResponse object) and dispatches them to the target servlet. The servlet processes the request using the data from HttpServletRequest and generates a response, which is then sent back to the client via HttpServletResponse.

sequenceDiagram
    participant Client
    participant WebServer
    participant ServletContainer
    participant Servlet

    Client->>WebServer: HTTP Request
    WebServer->>ServletContainer: Forward Request
    ServletContainer->>ServletContainer: Create HttpServletRequest & HttpServletResponse
    ServletContainer->>Servlet: Call service(req, resp)
    Servlet->>Servlet: Process Request (using HttpServletRequest)
    Servlet->>Servlet: Generate Response (using HttpServletResponse)
    Servlet-->>ServletContainer: Return
    ServletContainer-->>WebServer: Send Response
    WebServer-->>Client: HTTP Response

Sequence diagram illustrating the lifecycle of an HTTP request through a servlet container.

Key Information Accessible via HttpServletRequest

HttpServletRequest provides a rich set of methods to access various parts of the client's request. This includes parameters, headers, session information, and more. Being able to retrieve this information accurately is fundamental for building dynamic web applications.

Here are some of the most commonly used methods and the information they provide:

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

@WebServlet("/requestInfo")
public class RequestInfoServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<html><body>");
        out.println("<h1>HttpServletRequest Information</h1>");

        // 1. Request Parameters
        out.println("<h2>1. Request Parameters</h2>");
        String username = request.getParameter("username");
        out.println("<p>Username (from parameter 'username'): " + (username != null ? username : "N/A") + "</p>");

        out.println("<p>All Parameters:</p><ul>");
        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            String[] paramValues = request.getParameterValues(paramName);
            out.println("<li>" + paramName + ": ");
            for (String value : paramValues) {
                out.println(value + " ");
            }
            out.println("</li>");
        }
        out.println("</ul>");

        // 2. Request Headers
        out.println("<h2>2. Request Headers</h2>");
        out.println("<p>User-Agent: " + request.getHeader("User-Agent") + "</p>");
        out.println("<p>Host: " + request.getHeader("Host") + "</p>");
        out.println("<p>All Headers:</p><ul>");
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            out.println("<li>" + headerName + ": " + request.getHeader(headerName) + "</li>");
        }
        out.println("</ul>");

        // 3. Request URL and URI Information
        out.println("<h2>3. URL and URI Information</h2>");
        out.println("<p>Request URL: " + request.getRequestURL() + "</p>");
        out.println("<p>Request URI: " + request.getRequestURI() + "</p>");
        out.println("<p>Context Path: " + request.getContextPath() + "</p>");
        out.println("<p>Servlet Path: " + request.getServletPath() + "</p>");
        out.println("<p>Path Info: " + request.getPathInfo() + "</p>");
        out.println("<p>Query String: " + request.getQueryString() + "</p>");

        // 4. Session Information
        out.println("<h2>4. Session Information</h2>");
        HttpSession session = request.getSession(false); // Don't create if not exists
        if (session != null) {
            out.println("<p>Session ID: " + session.getId() + "</p>");
            out.println("<p>Session Creation Time: " + new java.util.Date(session.getCreationTime()) + "</p>");
            out.println("<p>Last Accessed Time: " + new java.util.Date(session.getLastAccessedTime()) + "</p>");
        } else {
            out.println("<p>No active session.</p>");
        }

        // 5. Request Attributes
        out.println("<h2>5. Request Attributes</h2>");
        request.setAttribute("myAttribute", "This is a request-scoped attribute");
        out.println("<p>Attribute 'myAttribute': " + request.getAttribute("myAttribute") + "</p>");

        out.println("</body></html>");
    }
}

Example Servlet demonstrating how to retrieve various types of information from HttpServletRequest.

Request Dispatching and Attributes

HttpServletRequest also plays a vital role in request dispatching. When you use RequestDispatcher to forward a request to another servlet or JSP, the same HttpServletRequest object (and HttpServletResponse) is passed along. This allows you to share data between components using request attributes. Attributes are key-value pairs that can be set on the request object and retrieved by subsequent components in the same request processing chain.

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/sourceServlet")
public class SourceServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Set an attribute in the request scope
        request.setAttribute("message", "Hello from SourceServlet!");

        // Get a RequestDispatcher for the target servlet
        RequestDispatcher dispatcher = request.getRequestDispatcher("/targetServlet");

        // Forward the request and response to the target servlet
        dispatcher.forward(request, response);
    }
}

@WebServlet("/targetServlet")
class TargetServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        response.getWriter().println("<html><body>");
        response.getWriter().println("<h1>Target Servlet</h1>");

        // Retrieve the attribute set by SourceServlet
        String message = (String) request.getAttribute("message");
        if (message != null) {
            response.getWriter().println("<p>Received message: " + message + "</p>");
        } else {
            response.getWriter().println("<p>No message received.</p>");
        }

        response.getWriter().println("</body></html>");
    }
}

Example of using request attributes and RequestDispatcher to share data between servlets.