ServletRequest Interface
ServletRequest: When a servlet is asked to handle a request (ServletRequest), it often requires specific information about the request in order to process it effectively. The servlet will regularly obtain the value of a form variable and utilise that value in its output.
The servlet may also need access to information about the environment in which it is running. For example, a servlet may need to find out about the actual user who is accessing the servlet, for authentication purposes.
This information is accessible via the ServletRequest and HttpServletRequest APIs. When a servlet receives a request, the server sends it a request object that implements one of these interfaces. The servlet can use this object to determine the actual request (e.g., protocol, URL, type), to access sections of the raw request (e.g., headers, input stream), and to obtain any client-specific request parameters (e.g., form variables, extra path information).
For instance, the getProtocol() method returns the protocol used by the request, while getRemoteHost() returns the name of the client host. The interfaces also provide methods that let servlet get information about the server (e.g., getServername(), getServerPort()).
HttpServletRequest provides a few new methods for dealing with HTTP-specific request data. GetHeaderNames(), for example, returns an enumeration of the names of all HTTP headers given with a request, whereas getHeader() returns a specific header value.
ServletRequest Interface
In example below shows a servlet that restricts access to users who are connecting via the HTTPS protocol, using Digest style authentication, and coming from a government site (a domain ending in .gov).
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class SecureRequestServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("<HTML>"); out.println("<HEAD><TITLE>Semi-Secure Request</TITLE></HEAD>"); out.println("<BODY>"); String remoteHost = req.getRemoteHost(); String scheme = req.getScheme(); String authType = req.getAuthType(); if((remoteHost == null) || (scheme == null) || (authType == null)) { out.println("Request Information Was Not Available."); return; } if(scheme.equalsIgnoreCase("https") && remoteHost.endsWith(".gov") && authType.equals("Digest")) { out.println("Special, secret information } else { out.println("You are not authorized to view this data."); } out.println("</BODY></HTML>"); }
The preceding example demonstrates how Checking Request Information to Restrict Servlet Access works for the site. This array typically includes only one string, but because some HTML form components (as well as non-HTTP oriented services) enable numerous selections or alternatives, the method always returns an array, even if it has a length of one.