MTI TEK
  • Home
  • About
  • LLMs
  • Docker
  • Kubernetes
  • Java
  • All Resources
Java Servlet | ServletRequest
  1. Introduction
  2. Reading HTTP Request Parameters
    1. Using Built-in Parameter Methods
    2. Direct Access to Request Body
  3. Working with Request Headers
  4. Managing Cookies
  5. Request Scope Attributes

  1. Introduction
    When the servlet container receives an HTTP request, it automatically creates a ServletRequest object that represents the details of the HTTP request, namely the HTTP method type, parameters, headers, and cookies. This object encapsulates all the information sent by the client and provides methods to access this data programmatically.

    The servlet container passes this ServletRequest object as a parameter to the service() method of the HttpServlet class. This method automatically dispatches to the corresponding doHTTP_METHOD_NAME method, which matches the HTTP method type of the request (GET, POST, HEAD, OPTIONS, TRACE, PUT, and DELETE). This dispatching mechanism allows servlets to handle different types of HTTP requests appropriately.

    Typically, you need to override the doHTTP_METHOD_NAME method in your servlet to write servlet-specific code. However, the default implementations of the doOptions(), doTrace(), and doHead() methods in the HttpServlet class are usually sufficient to handle HTTP OPTIONS, TRACE, and HEAD requests. For most web applications, you will primarily override doGet() and doPost() methods.
  2. Reading HTTP Request Parameters
    Parameters are data values that accompany HTTP requests and can be sent in two primary ways: manually added to the URL (query string parameters) or submitted through HTML forms where the "METHOD" attribute is set to "GET" or "POST". Understanding how to retrieve these parameters is fundamental to servlet development as they represent user input and configuration data.
    1. Using Built-in Parameter Methods
      The ServletRequest interface provides several convenient methods for accessing request parameters. These methods handle the parsing and decoding of parameters automatically, making them the preferred approach for most scenarios.
      • Enumeration<String> getParameterNames() :
        This method returns an enumeration containing the names of all request parameters sent with the HTTP request. The enumeration will be empty if no parameters were passed, but never null.

        Parameter names in the enumeration are unique, even if the HTML form contains multiple controls with the same name. This method is particularly useful when you need to iterate through all available parameters without knowing their names in advance.

      • String getParameter(String) :
        This method takes a parameter name as an argument and returns a string representing its value, or null if the parameter does not exist.

        The parameter name lookup is case-sensitive, so ensure exact matching of parameter names.

        If the parameter has multiple values (as with checkboxes, multi-select lists, or duplicate parameter names), this method returns only the first value encountered.

        Example:
        <form name="myForm" method="GET" action="MyServlet1">
          <input type="checkbox" name="myCheckbox1" value="0" />
          <input type="checkbox" name="myCheckbox1" value="1" />
        
          <input type="submit" name="mySubmit" value="Submit" />
        </form>
        If both checkboxes are checked, the URL string will look like: http://localhost:8080/mywebapp/MyServlet1?myCheckbox1=0&myCheckbox1=1&mySubmit=Submit

        The method call getParameter("myCheckbox1") will return either "0" or "1", but not both. In fact, the returned value corresponds to the first element of the array returned by String[] getParameterValues(String).

      • String[] getParameterValues(String) :
        This method takes a parameter name as an argument and returns an array of all values for that parameter, or null if the parameter does not exist.

        This is the preferred method when dealing with form elements that can have multiple values, such as checkboxes with the same name, multi-select dropdown lists, or when the same parameter name appears multiple times in the request.

        In the example above, getParameterValues("myCheckbox1") will return the array ["0", "1"].

        Always check for null return values before processing the array to avoid NullPointerException.

      • Map<String, String[]> getParameterMap() :
        This method returns a Map object (a hash table of key/value pairs), where:
        • the keys are unique parameter names (String objects).
        • and the values associated with these keys are arrays containing all the values of each parameter (String[] arrays).

        The returned map will be empty if no parameters were passed, but never null (behavior confirmed with Tomcat 7 and later versions).

        This method is particularly useful when you need to process all parameters programmatically or when forwarding parameters to other components.

        The returned map is immutable, so you cannot add, modify, or remove key-value pairs from it. Attempting to modify the map structure will result in an error. For example, the following code getParameterMap().put("myCheckbox1", new String[1]) will result in the following error:
        java.lang.IllegalStateException: No modifications are allowed to a locked ParameterMap
            org.apache.catalina.util.ParameterMap.put(ParameterMap.java:170)
        However, it is possible to modify the values within the array of a map entry, for example:
        String[] values1 = (String[]) request.getParameterMap().get("myCheckbox1");
        for (int i = 0; i < values1.length; i++)
            values1[i] = "New Value-" + i;
        Here is an example that displays the parameter names and values from the HTTP request (based on the form example above):
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.write("<html><head><title>test-getParameterMap</title></head><body>");
        
            Set<String> keys = request.getParameterMap().keySet();
            Iterator<String> keyIter = keys.iterator();
            while (keyIter.hasNext()) {
                String key = (String) keyIter.next();
                String[] values = (String[]) request.getParameterMap().get(key);
                out.write( " - key : " + key + " :<BR />" );
                for (int i = 0; i < values.length; i++) {
                    out.write( " " + (i+1) + ") value : " + values[i] + "<BR />" );
                }
                out.write( "<BR /><BR />" );
            }
        
            out.write("</body></html>");
            out.close();
        }
        Code execution result:
        - key : myCheckbox1 :
        1) value : 0
        2) value : 1
        
        - key : mySubmit :
        1) value : Submit
    2. Direct Access to Request Body
      In some advanced scenarios, you may need to read parameter values submitted via a form whose "METHOD" attribute is set to "POST" by directly accessing the HTTP request body. This approach is useful when dealing with custom content types, large payloads, or when you need to parse the data in a specific way that the standard parameter methods don't support.
      • java.io.BufferedReader getReader() :
        This method allows you to retrieve the request body in a character-based, non-binary format using the request's character encoding.
        The returned BufferedReader is suitable for reading text-based content such as form data, JSON, XML, or plain text.

      • ServletInputStream getInputStream() :
        This method allows you to retrieve the request body in binary format as a raw byte stream.
        This approach is necessary when handling file uploads, binary data, or when you need complete control over the data parsing process.

      You can use either of these methods, but not both on the same request. If you call getInputStream() first and then getReader(), you will get the following error:
      java.lang.IllegalStateException: getInputStream() has already been called for this request
          org.apache.catalina.connector.Request.getReader(Request.java:1212)
      And if you call getReader() first and then getInputStream(), you will get the following error:
      java.lang.IllegalStateException: getReader() has already been called for this request
          org.apache.catalina.connector.Request.getInputStream(Request.java:1058)
      Additionally, if you have already called any of the parameter methods (getParameter(), getParameterValues(), or getParameterMap()), the servlet container may have already consumed the request body, making these methods unavailable.

      Here is an example that displays the names and values of the HTTP request parameters by parsing the request body directly:

      HTML page:
      <form name="myForm" method="POST" action="MyServlet1">
        <input type="checkbox" name="myCheckbox1" value="0" />
        <input type="checkbox" name="myCheckbox1" value="1" />
      
        <input type="submit" name="mySubmit" value="Submit" />
      </form>
      Servlet code:
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          response.setContentType("text/html");
          PrintWriter out = response.getWriter();
          out.write("<html><head><title>test-getInputStream</title></head><body>");
      
          BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
          String requestBodyLine;
          while ((requestBodyLine = bufferedReader.readLine()) != null) {
              StringTokenizer stringTokenizer = new StringTokenizer(requestBodyLine, "&");
              while (stringTokenizer.hasMoreTokens()) {
                  out.write(stringTokenizer.nextToken() + "<br />");
              }
          }
      
          out.write("</body></html>");
          out.close();
      }
      Code execution result:
      myCheckbox1=0
      myCheckbox1=1
      mySubmit=Submit
  3. Working with Request Headers
    HTTP headers contain important metadata about the request, including information about the client browser, accepted content types, authentication credentials, and custom application-specific data. The ServletRequest interface provides several methods to access and process these headers effectively.
    • Enumeration<String> getHeaderNames() :
      Returns an enumeration of all the request header names present in the HTTP request.
      Header names are case-insensitive according to the HTTP specification, but this method returns them as they were sent by the client.
      The servlet container may deny access to certain headers for security reasons; in that case, those headers will not appear in the enumeration, but the method will never return null.

    • String getHeader(String) :
      Returns the value of a specific request header identified by the header name.
      Header name matching is case-insensitive, so "Content-Type", "content-type", and "CONTENT-TYPE" will all match the same header.
      If the header has multiple values, this method returns the first value. Returns null if the header does not exist.

    • Enumeration<String> getHeaders(String) :
      Returns all the values of a specific request header as an enumeration.
      This method is useful when a header can have multiple values, such as the "Accept" header which can list multiple content types.
      The servlet container may deny access to certain headers; in that case, an empty enumeration may be returned, but never null.

    • long getDateHeader(String) :
      Returns the value of a request header as a long value representing the number of milliseconds since January 1, 1970 GMT, or -1 if the header does not exist.
      This method is specifically designed for headers that contain date values, such as "If-Modified-Since" or custom date headers.
      This method throws a java.lang.IllegalArgumentException if the header value cannot be converted to a valid date format.

    • int getIntHeader(String) :
      Returns the value of a request header as an integer, or -1 if the header does not exist.
      This method is useful for headers that contain numeric values, such as "Content-Length" or custom numeric headers.
      This method throws a java.lang.NumberFormatException if the header value cannot be converted to a valid integer.

  4. Managing Cookies
    Cookies are small pieces of data stored by the client's browser and sent back to the server with each request. They are commonly used for session management, user preferences, and tracking user behavior across multiple requests. The ServletRequest interface provides methods to access cookies sent by the client.
    • Cookie[] getCookies() :
      This method returns an array of Cookie objects representing all cookies sent by the client with the HTTP request, or null if no cookies are present.
      Always check for null return values before processing the cookie array to avoid NullPointerException.
      Each cookie in the array contains the name, value, and potentially other attributes like domain, path, and expiration information.

    A Cookie object encapsulates the cookie data and has:
    - a name (String) - the identifier for the cookie;
    - a value (String) - the data associated with the cookie;
    - and other optional attributes such as expiration date, domain scope, path restriction, and security flags.

    The constructor Cookie(String name, String value) creates a new Cookie object with the specified name and value.
    Common methods for working with Cookie objects include getName(), getValue(), getDomain(), getPath(), and getMaxAge().
  5. Request Scope Attributes
    Request attributes provide a mechanism for storing and sharing data within the scope of a single HTTP request. Unlike parameters, which are sent by the client, attributes are set programmatically by server-side components and can store any Java object. This feature is particularly useful for passing data between servlets, JSPs, and other components within the same request processing cycle.

    Attributes are managed using an internal map structure that associates each attribute name with a Java object.
    You can add, remove, and read the value of an attribute during request processing.
    Attribute names are unique within the request scope, so you cannot have two attributes with the same name simultaneously.

    Here are the methods used to manage attributes in the Request scope:
    void setAttribute(String, Object)
    
    void removeAttribute(String)
    
    Object getAttribute(String)
    
    Enumeration<String> getAttributeNames()
    • void setAttribute(String ATTRIBUTE_NAME, Object OBJ)
      This method stores an object in the request scope with the specified attribute name.
      - ATTRIBUTE_NAME: The name of the attribute that will be mapped to the object. This name serves as the key for later retrieval.
      - OBJ: The object to be stored. If this parameter is null, the attribute will be removed from the request scope (same effect as calling removeAttribute).
      The object can be of any type - String, Integer, custom Java objects, collections, etc.

    • void removeAttribute(String ATTRIBUTE_NAME)
      This method removes an attribute from the request scope.
      - ATTRIBUTE_NAME: The name of the attribute to be removed from the Request scope.
      If no attribute with the specified name exists, this method has no effect and does not throw an exception.

    • Object getAttribute(String ATTRIBUTE_NAME)
      This method retrieves an object from the request scope.
      - Returns the object associated with the attribute ATTRIBUTE_NAME.
      - Returns null if no attribute with that name exists in the Request scope.
      Since the return type is Object, you will typically need to cast the returned value to the appropriate type.

    • Enumeration<String> getAttributeNames()
      This method provides access to all attribute names currently stored in the request scope.
      - Returns an enumeration containing the names of all attributes in the Request scope.
      - Returns an empty enumeration if no attributes exist in the Request scope, but never returns null.
      This method is useful for debugging or when you need to iterate through all available attributes.

    Important considerations when using these methods:
    • The attribute name can be any string. However, it is recommended to use a naming convention that includes the domain and the web application name to avoid conflicts, such as "com.companyname.MYWEBAPPLI.MYATTRIBUTENAME".
      This practice becomes especially important in complex applications or when using third-party libraries that might also set request attributes.

    • Some attribute names are reserved by the Servlet specification and should not be used by application code. This applies to all names prefixed with "java.*", "javax.*", "jakarta.*", and "sun.*".
      Using reserved names may result in undefined behavior or conflicts with container operations.

    • You cannot have two attributes with the same name in the request scope; if setAttribute is called with a name that already exists, the existing value will be replaced with the new one.
      This replacement happens silently without any warning or exception.

© 2025 mtitek