HttpServletRequest Interface with Example

The HttpServletRequest interface enables a servlet to obtain information about a client request.

Check out : Servlet + JSP + JDBC + MySQL Examples

HttpServletRequest interface extends the ServletRequest interface to provide request information for HTTP servlets. The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service methods (doGet, doPost, etc).
For instance, here is the signature of the HttpServlet.doGet() method:
protected void doGet(
    HttpServletRequest request,
    HttpServletResponse response)
      throws ServletException, IOException {}

HttpServletRequest Interface Overview

The HttpServletRequest breaks a request down into parsed elements, such as request URI, query arguments and headers. Various get methods allow you to access different parts of the request.
  • Request-URI
  • Parameters
  • Attributes
  • ServletInputStream

requestURI

The requestURI deals with the URL sent by the browser. 
For example:
http://localhost:80/MyWebApplication/personal/info/top.html?info=intro
Given the request http://localhost:80/MyWebApplication/personal/info/top.html?info=intro here are the various ways of accessing the request URI and query string:
String uri =  request.getRequestURI();
String contextPath = request.getContextPath();
String servletPath = request.getServletPath();
String pathInfo = request.getPathInfo();
String queryStr = request.getQueryString();
Below is the output of the above API:
  • GetRequestURI - /MyWebApplication/personal/info/top.html
  • GetContextPath - /MyWebApplication
  • GetServletPath - /personal
  • GetPathInfo - /info/top.html
  • GetPathTranslated - /www/docs/info/top.html
  • GetQueryString - info=intro

Parameters

The HttpServletRequest provides methods for accessing parameters of a request. The type of request determines where the parameters come from. In most implementations, a GET request takes the parameters from the query string, while a POST request takes the parameters from the posted arguments.
The methods getParameter(), getParameterValues(), and getParameterNames() are offered as ways to access these arguments. For example:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException {
 
 // parameters related API's
 String username = request.getParameter("username");
 Enumeration<String> e = request.getParameterNames();
 String str;
 while (e.hasMoreElements()) {
  str = e.nextElement();
  printWriter.println("<br>Param Name: " + str);
 }
 
 String[] values = request.getParameterValues("values");
}

Headers

The request headers are a name, value pairs sent by the browser along with the HTTP request. The request headers contain information about e.g. what browser software is being used, what file types the browser is capable of receiving etc.
You can access the request headers from the HttpRequest object like this:
String contentLength = request.getHeader("Content-Length"); 

InputStream

If the browser sends an HTTP POST request, request parameters and other potential data are sent to the server in the HTTP request body. To give you access to the request body of an HTTP POST request, you can obtain an InputStream pointing to the HTTP request body. Here is how it is done:
InputStream requestBodyInput = request.getInputStream();    

Session

HttpServletRequest interface provides a getSession() method, which returns the current session associated with this request, or if the request does not have a session, creates one.
The session object can hold information about a given user, between requests. So, if you set an object into the session object during one request, it will be available for you to read during any subsequent requests within the same session time scope.
Here is how you access the session object from the HttpServletRequest object:
HttpSession session = request.getSession();

ServletContext

You can access the ServletContext object from the HttpServletRequest object too. The ServletContext contains meta information about the web application. Here is how you access the ServletContext object from the HttpServletRequest object:
ServletContext context = request.getSession().getServletContext();

HttpServletRequest Interface Class Diagram

Here is a class diagram shows a HttpServletRequest interface extends the ServletRequest interface to provide request information for HTTP servlets.

HttpServletRequest Interface Example

In this example, we will demonstrate all the important methods of HttpServletRequest interface:
package net.javaguides.servlet.tutorial.httpservlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletContext;
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;

@WebServlet(urlPatterns = "/httpservletrequest")
public class HttpServletRequestExample extends HttpServlet {

    private static final long serialVersionUID = 1 L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter printWriter = response.getWriter();

        // uri related API's
        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String servletPath = request.getServletPath();
        String pathInfo = request.getPathInfo();
        String queryStr = request.getQueryString();

        // parameters related API's
        String username = request.getParameter("username");
        Enumeration < String > e = request.getParameterNames();
        String str;
        while (e.hasMoreElements()) {
            str = e.nextElement();
            printWriter.println("<br>Param Name: " + str);
        }

        String[] values = request.getParameterValues("values");

        // Attributes related API's
        Object attribute = request.getAttribute("username");

        // session methods
        HttpSession httpSession = request.getSession();

        // ServletContext
        ServletContext context = request.getSession().getServletContext();
    }
}

Reference

Servlet 4.0 Basic Examples

Comments