Recipe 18.1 Examining HTTP Request Headers in a Servlet


Problem

You want to examine the HTTP request headers in a servlet.

Solution

Use the javax.servlet.http.HttpServletRequest.getHeaderNames( ) and getHeader( ) methods to access the names and values of various request headers.

Discussion

The HttpServletRequest.getHeaderNames( ) method returns all of the request header names for an incoming request. You can then obtain the value of a specific header by providing the header name to the method HttpServletRequest.getHeader( ) method. Example 18-1 gets an Enumeration of header names in the servlet's doGet( ) method, and then displays each header and value on its own line in the resulting HTML page.

Example 18-1. A servlet displays request headers and values
 package com.jspservletcookbook;  import java.util.Enumeration; import javax.servlet.*; import javax.servlet.http.*;  public class RequestHeaderView extends HttpServlet {   public void doGet(HttpServletRequest request,      HttpServletResponse response) throws ServletException,       java.io.IOException {  //get an Enumeration of all the request header names       Enumeration enum = request.getHeaderNames( );  response.setContentType("text/html");       java.io.PrintWriter out = response.getWriter( );       out.println(           "<html><head><title>Request Header View</title></head><body>");       out.println("<h2>Request Headers</h2>");       String header = null;  //display each request header name and value         while (enum.hasMoreElements( )){           header = (String) enum.nextElement( );       //getHeader returns null if a request header of that name does not       //exist in the request       out.println("<strong>"+header+"</strong>"+": "+           request.getHeader(header)+"<br>" );  }            out.println("</body></html>");   } //doGet } 

Figure 18-1 shows the RequestHeaderView servlet's output.

Figure 18-1. A servlet shows the request header names and values
figs/jsjc_1801.gif

See Also

Recipe 18.2 on examining request headers in a JSP; Recipe 18.3 on using a filter to wrap the request and forward it along the filter chain; Recipe 18.6 on using a listener to track requests ; Chapter 7 on handling request parameters and JavaBean properties with servlets, JSPs, and filters.



Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net