ServletRequest To Get Request Data

ServletRequest instance is used to retrieve request information send from client users. We commonly use the HttpServletRequest object in java servlet code. You can use it to collect content length, content type, parameter name-value pairs, HTTP header, etc. You can click here to see a detailed introduction to the HttpServletRequest object method. We will give you 5 java code examples in this article to show you how to use them to get client data.

1. Example 1: Get request parameter value in URL.

  1. Suppose the URL is http://localhost:8080/Dev2qaWebAppExample/GetRequestParameter?userName=Jerry. There is a request parameter “userName” in the URL.
  2. You can use the below java code in the doGet(HttpServletRequest req, HttpServletResponse resp) method to retrieve the parameter’s value. Because the HTTP request method for this kind of URL is GET. So the servlet doGet() method will be invoked.
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         /* Use HttpServletRequest's getParameter method to get the parameter value in request url.*/
         String userName = req.getParameter("userName");
         if(userName!=null && !"".equals(userName))
         {
             /* If the parameter's value is not null and empty then print below to the return page.*/
             resp.getWriter().println("Hello " + userName + " , you are welcome to servlet world.");
         }
     }

2. Example 2: Get request parameter value in HTML form.

  1. Add following HTML code in index.jsp which is the web application’s welcome file.
    <form action="/Dev2qaWebAppExample/GetRequestParameter" method="post">
        <input type="text" id="userName" name="userName"/>
        <input type="submit" value="Submit"/>
    </form>
  2. Please note the input text box must have a name attribute. And it’s value should be userName. If the input text box does not has a name attribute, then you can not get the submitted text box’s value by the HttpServletRequest object’s getParameter() method in the servlet doGet() method.
  3. The java code to get the request parameter in Example 2 is the same as Example 1.

3. Example 3: List all the request headers’ name and value.

  1. HttpServletRequest‘s getHeaderNames() method will return all http header name in the request. And getHeader(String headerName) method will return the header value for it.
     String action = req.getParameter("action");
     if(action!=null && !"".equals(action))
     {
       if("showHeaders".equalsIgnoreCase(action))
       {
           PrintWriter pw = resp.getWriter();
           pw.println("Request header list.");
           Enumeration paramEnu = req.getHeaderNames();
           while(paramEnu.hasMoreElements())
           {
             Object nameObj = paramEnu.nextElement();
             if(nameObj!=null)
             {
               String name = (String)nameObj;
               String value = req.getHeader(name);
               pw.println(name + " = " + value);
             }
           }
        }
     }
  2. We use the action request parameter to switch request actions. If it’s value is “showHeaders” then the java code will list all the HTTP request header names and value pairs. You should use the URL http://localhost:8080/Dev2qaWebAppExample/GetRequestParameter?action=showHeaders to invoke the above java code.
  3. You can also invoke the above java code by form submit. Add below HTML code in index.jsp.
    <form action="/Dev2qaWebAppExample/GetRequestParameter" method="post">
        <input type="hidden" name="action" value="showHeaders" />
        <input type="text" id="userName" name="userName"/>
        <input type="submit" value="Submit"/>
    </form>
  4. Please notice the name attribute of the hidden input form field. The name attribute must be specified otherwise you can not get it’s value using HttpServletRequest object’s getParameter() method. When you click Submit button, you will see the HTTP POST request header values.
  5. You can notice that there has more request header in HTTP post request method.
  6. Below are some example HTTP request headers explanations.
  7. host: The requested web server’s IP and port.
  8. content-length: The submitted data’s length.
  9. user-agent: The browser type and version information.
  10. accept: Specify the type of content data that the client can accept.
  11. referer: The previous page URL that leads to the current page.
  12. accept-language: Specify the languages that the client can accept.
  13. Click here to learn detailed explanation for HTTP headers.

4. Example 4: Get client IP and port that sends the request.

  1. getRemoteAddr(): Get the client IP address or the IP address of the last proxy that request to the server.
  2. getRemoteHost(): Get the client hostname or the hostname of the last proxy that request to the server.
  3. getRemotePort(): Get the client port or the port of the last proxy that request to the server.
  4. If method getRemoteAdrr() return a null or empty string. This means the client request you through a proxy server. Then you need to use req.getHeader(“X-Forwarded-For”) to get the IP address that the last proxy server added in the HTTP header.
    else if("getClientInfo".equalsIgnoreCase(action))
    {
        String remoteAddr = req.getRemoteAddr();
     
        /* This means the client request to you through a proxy server. */
        if(remoteAddr==null || "".equals(remoteAddr))
        {
           remoteAddr = req.getHeader("X-Forwarded-For");
        }
     
        /* This means you just access the web application in localhost. */
        if("0:0:0:0:0:0:0:1".equalsIgnoreCase(remoteAddr))
        {
           /* Get localhost inetAddress object */
           InetAddress inetAddressObj = InetAddress.getLocalHost();
           /* Get localhost real ip*/
           remoteAddr = inetAddressObj.getHostAddress();
        }
     
        /* Get request client port. */
        int remotePort = req.getRemotePort();
     
        pw.println("Remote Addr = " + remoteAddr);
        pw.println("Remote Port = " + remotePort);
     }

5. Example 5: List all cookie values.

  1. A cookie is a small piece of data stored in a web browser. The cookie data is sent from the web server. Click here to learn more about HTTP cookie.
    else if("listCookieValues".equalsIgnoreCase(action))
    {
       Cookie cookieArr[] = req.getCookies();
     
       if(cookieArr!=null)
       {
           StringBuffer cookieBuf = new StringBuffer();
           int len = cookieArr.length;
           for(int i=0;i<len;i++)
           {
              Cookie cookie = cookieArr[i];
              cookieBuf.append("cookie name = " + cookie.getName() + " , ");
              cookieBuf.append("value = " + cookie.getValue() + " , ");
              cookieBuf.append("domain = " + cookie.getDomain() + " , ");
              cookieBuf.append("comment = " + cookie.getComment() + " , ");
              cookieBuf.append("maxage = " + cookie.getMaxAge() + " , ");
              cookieBuf.append("path = " + cookie.getPath() + " , ");
              cookieBuf.append("version = " + cookie.getVersion() + " , ");
    
              pw.println(cookieBuf.toString());
              cookieBuf.delete(0, cookieBuf.length());
           }
       }
    }

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Index