Get the online training

Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com

Web Service

Handling the Client Request: HTTP Request Headers

  • Reading HTTP request headers

  • Building a table of all the request headers

  • Understanding the various request headers

  • Reducing download times by compressing pages

  • Differentiating among types of browsers

HTTP request headers are distinct from the form data discussed in the previous chapter. Form data results directly from user input and is sent as part of the URL for GET requests and on a separate line for POST requests. Request headers, on the other hand, are indirectly set by the browser and are sent immediately following the initial GET or POST request

line. For instance, the following example shows an HTTP request that might result from submitting a book-search request to a servlet at http://www.somebookstore.com/search. The request includes the headers Accept, Accept-Encoding, Connection, Cookie, Host, Referer, and User-Agent, all of which might be important to the operation of the servlet,

but none of which can be derived from the form data or deduced auto-GET /search?keywords=servlets+jsp HTTP/1.1

Accept: image/gif, image/jpg, */*

Accept-Encoding: gzip

Connection: Keep-Alive

Cookie: userID=id456578

Host: www.somebookstore.com

Referer: http://www.somebookstore.com/findbooks.html

User-Agent: Mozilla/4.7 [en] (Win98; U)

Reading Request Headers from Servlets


The getCookies method returns the contents of the Cookie
header, parsed and stored in an array of Cookie objects.

getAuthType and getRemoteUser

The getAuthType and getRemoteUser methods break the
Authorization header into its component pieces.


The getContentLength method returns the value of the
Content-Length header (as an int).


The getContentType method returns the value of the
Content-Type header (as a String).

• getDateHeader and getIntHeader

The getDateHeader and getIntHeader methods read the
specified header and then convert them to Date and int values,


Rather than looking up one particular header, you can use the
getHeaderNames method to get an Enumeration of all header
names received on this particular request.


In most cases, each header name appears only once in the
request. Occasionally, however, a header can appear multiple
times, with each occurrence listing a separate value.

Accept-Language is one such example. If a header name is
repeated in the request, version 2.1 servlets cannot access the
later values without reading the raw input stream, since
getHeader returns the value of the first occurrence of the
header only. In version 2.2, however, getHeaders returns an
Enumeration of the values of all occurrences of the header.
Finally, in addition to looking up the request headers, you can get information
on the main request line itself, also by means of methods in Http-


The getMethod method returns the main request method
(normally GET or POST, but things like HEAD, PUT, and DELETE
are possible).


The getRequestURI method returns the part of the URL that
comes after the host and port but before the form data. For
example, for a URL of
getRequestURI would return


Lastly, the getProtocol method returns the third part of the
request line, which is generally HTTP/1.0 or HTTP/1.1. Servlets

HTTP 1.1 Request Headers

Access to the request headers permits servlets to perform a number of optimizations
and to provide a number of features not otherwise possible. This
section presents each of the possible HTTP 1.1 request headers along with a
brief summary of how servlets can make use of them.


This header specifies the MIME types that the browser or other client
can handle. A servlet that can return a resource in more than one format can examine the Accept header to decide which format to use.


This header indicates the character sets (e.g., ISO-8859-1) the browser
can use.


This header designates the types of encodings that the client knows how to handle. If it receives this header, the server is free to encode the page by using the format specified (usually to reduce transmission time), sending the Content-Encoding response header to indicate that it has
done so. This encoding type is completely distinct from the MIME type of the actual document (as specified in the Content-Type response header), since this encoding is reversed before the browser decides what to do with the content. On the other hand, using an encoding the browser doesn’t understand results in totally incomprehensible pages. Consequently, it is critical that you explicitly check the Accept-Encoding header before using any type of content encoding. Values of gzip or compress are the two standard possibilities.


This header specifies the client’s preferred languages, in case the servlet can produce results in more than one language. The value of the header should be one of the standard language codes such as en, en-us, da, etc. 


This header is used by clients to identify themselves when accessing
password-protected Web pages. 

This header can be used by the client to specify a number of options for how pages should be cached by proxy servers. The request header is usually ignored by servlets, but the Cache-Control response header can be valuable to indicate that a page is constantly changing and shouldn’t be cached. 


This header tells whether or not the client can handle persistent HTTP connections. These let the client or other browser retrieve multiple files (e.g., an HTML file and several associated images) with a single socket connection, saving the overhead of negotiating several independent connections. With an HTTP 1.1 request, persistent connections are the default, and the client must specify a value of close for this header to use old-style connections. In HTTP 1.0, a value of keep-alive means
that persistent connections should be used. Each HTTP request results in a new invocation of a servlet, regardless of whether the request is a separate connection. That is, the server invokes the servlet only after the server has already read the HTTP request. This means that servlets need help from the server to handle persistent connections. Consequently, the servlet’s job is just to make it possible for the server to use persistent connections, which is done by sending a Content-Length response header. 


This header is only applicable to POST requests and gives the size of the POST data in bytes. Rather than calling request.getIntHeader("Content- Length"), you can simply use request.getContentLength().


Although this header is usually used in responses from the server, it can also be part of client requests when the client attaches a document as the POST data or when making PUT requests. You can access this header with the shorthand getContentType method of HttpServletRequest.


This header is used to return cookies to servers that previously sent them to the browser.This rarely used header lets the client tell the server what kinds of behaviors it expects. The one standard value for this header, 100-continue, is sent by a browser that will be sending an attached document and wants to know if the server will accept it. The server should send a status code of either 100 (Continue) or 417 (Expectation Failed) in such a case.


This header gives the e-mail address of the person responsible for the HTTP request. Browsers do not send this header, but Web spiders (robots) often set it as a courtesy to help identify the source of server
overloading or repeated improper requests.


Browsers are required to specify this header, which indicates the host and port as given in the original URL. Due to request forwarding and machines that have multiple hostnames, it is quite possible that the
server could not otherwise determine this information. This header is not new in HTTP 1.1, but in HTTP 1.0 it was optional, not required.


This header identifies the browser or other client making the request and can be used to return different content to different types of browsers. Be wary of this usage, however; relying on a hard-coded list
of browser versions and associated features can make for unreliable and hard-to-modify servlet code. Whenever possible, use something specific in the HTTP headers instead.

package myservlet;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException  {

    PrintWriter out = response.getWriter();

    out.print("<br><br>User agent Header value is :- "
        + request.getHeader("user-agent"));

    Enumeration e = request.getHeaderNames();
    out.print("<br><br><table border='1' style='color:blue'><tr><th> Header name
</th><th>Header value</th></tr>"
    while (e.hasMoreElements()) {
      Object object = (Objecte.nextElement();
      out.print("<tr><td>" + object + "</td><td>"
          + request.getHeader(object.toString()) "</td></tr>");    

 Download Source