Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

2.8 The Server Response: HTTP Response Headers

As discussed in the previous section, a response from a Web server normally consists of a status line, one or more response headers (one of which must be Content-Type), a blank line, and the document. To get the most out of your servlets, you need to know how to use the status line and response headers effectively, not just how to generate the document.

Setting the HTTP response headers often goes hand in hand with setting the status codes in the status line, as discussed in the previous section. For example, all the "document moved" status codes (300 through 307) have an accompanying Loca_tion header, and a 401 (Unauthorized) code always includes an accompanying WWW-Authenticate header. However, specifying headers can also play a useful role even when no unusual status code is set. Response headers can be used to specify cookies, to supply the page modification date (for client-side caching), to instruct the browser to reload the page after a designated interval, to give the file size so that persistent HTTP connections can be used, to designate the type of document being generated, and to perform many other tasks. This section gives a brief summary of the handling of response headers. See Chapter 7 of Core Servlets and JavaServer Pages (available in PDF at http://www.moreservlets.com) for more details and examples.

Setting Response Headers from Servlets

The most general way to specify headers is to use the setHeader method of HttpServletResponse. This method takes two strings: the header name and the header value. As with setting status codes, you must specify headers before returning the actual document.

In addition to the general-purpose setHeader method, HttpServletResponse also has two specialized methods to set headers that contain dates and integers:

  • setDateHeader(String header, long milliseconds) This method saves you the trouble of translating a Java date in milliseconds since 1970 (as returned by System.currentTimeMillis, Date.getTime, or Calendar.getTimeInMillis) into a GMT time string.

  • setIntHeader(String header, int headerValue) This method spares you the minor inconvenience of converting an int to a String before inserting it into a header.

HTTP allows multiple occurrences of the same header name, and you sometimes want to add a new header rather than replace any existing header with the same name. For example, it is quite common to have multiple Accept and Set-Cookie headers that specify different supported MIME types and different cookies, respectively. With servlets version 2.1, setHeader, setDateHeader, and setIntHeader always add new headers, so there is no way to "unset" headers that were set earlier (e.g., by an inherited method). With servlets versions 2.2 and 2.3, setHeader, setDateHeader, and setIntHeader replace any existing headers of the same name, whereas addHeader, addDateHeader, and addIntHeader add a header regardless of whether a header of that name already exists. If it matters to you whether a specific header has already been set, use containsHeader to check.

Finally, HttpServletResponse also supplies a number of convenience methods for specifying common headers. These methods are summarized as follows.

  • setContentType This method sets the Content-Type header and is used by the majority of servlets.

  • setContentLength This method sets the Content-Length header, which is useful if the browser supports persistent (keep-alive) HTTP connections.

  • addCookie This method inserts a cookie into the Set-Cookie header. There is no corresponding setCookie method, since it is normal to have multiple Set-Cookie lines. See Section 2.9 (Cookies) for a discussion of cookies.

  • sendRedirect As discussed in the previous section, the sendRedirect method sets the Location header as well as setting the status code to 302. See Listing 2.12 for an example.

Understanding HTTP 1.1 Response Headers

Following is a summary of the most useful HTTP 1.1 response headers. A good understanding of these headers can increase the effectiveness of your servlets, so you should at least skim the descriptions to see what options are at your disposal. You can come back for details when you are ready to use the capabilities.

These headers are a superset of those permitted in HTTP 1.0. The official HTTP 1.1 specification is given in RFC 2616. The RFCs are online in various places; your best bet is to start at http://www.rfc-editor.org/ to get a current list of the archive sites. Header names are not case sensitive but are traditionally written with the first letter of each word capitalized.

Be cautious in writing servlets whose behavior depends on response headers that are only available in HTTP 1.1, especially if your servlet needs to run on the WWW "at large" rather than on an intranet—many older browsers support only HTTP 1.0. It is best to explicitly check the HTTP version with request.getRequestProtocol before using new headers.


The Allow header specifies the request methods (GET, POST, etc.) that the server supports. It is required for 405 (Method Not Allowed) responses. The default service method of servlets automatically generates this header for OPTIONS requests.


This useful header tells the browser or other client the circumstances in which the response document can safely be cached. It has the following possible values:

  • public. Document is cacheable, even if normal rules (e.g., for password-protected pages) indicate that it shouldn't be.

  • private. Document is for a single user and can only be stored in private (nonshared) caches.

  • no-cache. Document should never be cached (i.e., used to satisfy a later request). The server can also specify "no-cache="header1,header2,...,headerN"" to indicate the headers that should be omitted if a cached response is later used. Browsers normally do not cache documents that were retrieved by requests that include form data. However, if a servlet generates different content for different requests even when the requests contain no form data, it is critical to tell the browser not to cache the response. Since older browsers use the Pragma header for this purpose, the typical servlet approach is to set both headers, as in the following example.

    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
  • no-store. Document should never be cached and should not even be stored in a temporary location on disk. This header is intended to prevent inadvertent copies of sensitive information.

  • must-revalidate. Client must revalidate document with original server (not just intermediate proxies) each time it is used.

  • proxy-revalidate. This is the same as must-revalidate, except that it applies only to shared caches.

  • max-age=xxx. Document should be considered stale after xxx seconds. This is a convenient alternative to the Expires header but only works with HTTP 1.1 clients. If both max-age and Expires are present in the response, the max-age value takes precedence.

  • s-max-age=xxx. Shared caches should consider the document stale after xxx seconds.

The Cache-Control header is new in HTTP 1.1.


A value of close for this response header instructs the browser not to use persistent HTTP connections. Technically, persistent connections are the default when the client supports HTTP 1.1 and does not specify a Connection: close request header (or when an HTTP 1.0 client specifies Connection: keep-alive). However, since persistent connections require a Con_tent- Length response header, there is no reason for a servlet to explicitly use the Connection header. Just omit the Con_tent-Length header if you aren't using persistent connections.


This header indicates the way in which the page was encoded during transmission. The browser should reverse the encoding before deciding what to do with the document. Compressing the document with gzip can result in huge savings in transmission time; for an example, see Section 9.5.


The Content-Language header signifies the language in which the document is written. The value of the header should be one of the standard language codes such as en, en-us, da, etc. See RFC 1766 for details on language codes (you can access RFCs online at one of the archive sites listed at http://www.rfc-editor.org/).


This header indicates the number of bytes in the response. This information is needed only if the browser is using a persistent (keep-alive) HTTP connection. See the Connection header for determining when the browser supports persistent connections. If you want your servlet to take advantage of persistent connections when the browser supports it, your servlet should write the document into a ByteArrayOutputStream, look up its size when done, put that into the Content-Length field with response.setContentLength, then send the content by byteArrayStream.writeTo(response.getOutputStream()). See Core Servlets and JavaServer Pages Section 7.4 for an example.


The Content-Type header gives the MIME (Multipurpose Internet Mail Extension) type of the response document. Setting this header is so common that there is a special method in HttpServletResponse for it: setContentType. MIME types are of the form maintype/subtype for officially registered types and of the form maintype/x-subtype for unregistered types. Most servlets specify text/html; they can, however, specify other types instead.

In addition to a basic MIME type, the Content-Type header can also designate a specific character encoding. If this is not specified, the default is ISO-8859_1 (Latin). For example, the following instructs the browser to interpret the document as HTML in the Shift_JIS (standard Japanese) character set.

response.setContentType("text/html; charset=Shift_JIS");

Table 2.1 lists some the most common MIME types used by servlets. RFC 1521 and RFC 1522 list more of the common MIME types (again, see http://www.rfc-editor.org/ for a list of RFC archive sites). However, new MIME types are registered all the time, so a dynamic list is a better place to look. The officially registered types are listed at http://www.isi.edu/in-notes/iana/assignments/media-types/media-types. For common unregistered types, http://www.ltsw.se/knbase/internet/mime.htp is a good source.

Table 2.1 Common MIME Types




Microsoft Word document


Unrecognized or binary data


Acrobat (.pdf) file


PostScript file


Lotus Notes file


Excel spreadsheet


PowerPoint presentation


Gzip archive


JAR file


Serialized Java object


Java bytecode (.class) file


Zip archive


Sound file in .au or .snd format




MIDI sound file


AIFF sound file


Microsoft Windows sound file


GIF image


JPEG image


PNG image


TIFF image


X Windows bitmap image


HTML cascading style sheet


HTML document


Plain text




MPEG video clip


QuickTime video clip


This header stipulates the time at which the content should be considered out-of-date and thus no longer be cached. A servlet might use this for a document that changes relatively frequently, to prevent the browser from displaying a stale cached value. Furthermore, since some older browsers support Pragma unreliably (and Cache-Control not at all), an Expires header with a date in the past is often used to prevent browser caching.

For example, the following would instruct the browser not to cache the document for more than 10 minutes.

 long currentTime = System.currentTimeMillis();
long tenMinutes = 10*60*1000; // In milliseconds
response.setDateHeader("Expires", currentTime + tenMinutes);

Also see the max-age value of the Cache-Control header.


This very useful header indicates when the document was last changed. The client can then cache the document and supply a date by an If-Modi_fied-Since request header in later requests. This request is treated as a conditional GET, with the document being returned only if the Last-Modified date is later than the one specified for If-Modi_fied-Since. Otherwise, a 304 (Not Modified) status line is returned, and the client uses the cached document. If you set this header explicitly, use the setDateHeader method to save yourself the bother of formatting GMT date strings. However, in most cases you simply implement the getLastModified method (see Core Servlets and JavaServer Pages Section 2.8) and let the standard service method handle If-Modified-Since requests.


This header, which should be included with all responses that have a status code in the 300s, notifies the browser of the document address. The browser automatically reconnects to this location and retrieves the new document. This header is usually set indirectly, along with a 302 status code, by the send_Redirect method of HttpServletResponse. An example is given in the previous section (Listing 2.12).


Supplying this header with a value of no-cache instructs HTTP 1.0 clients not to cache the document. However, support for this header was inconsistent with HTTP 1.0 browsers, so Expires with a date in the past is often used instead. In HTTP 1.1, Cache-Control: no-cache is a more reliable replacement.


This header indicates how soon (in seconds) the browser should ask for an updated page. For example, to tell the browser to ask for a new copy in 30 seconds, you would specify a value of 30 with

response.setIntHeader("Refresh", 30)

Note that Refresh does not stipulate continual updates; it just specifies when the next update should be. So, you have to continue to supply Refresh in all subsequent responses. This header is extremely useful because it lets servlets return partial results quickly while still letting the client see the complete results at a later time. For an example, see Section 7.3 of Core Servlets and JavaServer Pages (in PDF at http://www.moreservlets.com).

Instead of having the browser just reload the current page, you can specify the page to load. You do this by supplying a semicolon and a URL after the refresh time. For example, to tell the browser to go to http://host/path after 5 seconds, you would do the following.

response.setHeader("Refresh", "5; URL=http://host/path/")

This setting is useful for "splash screens," where an introductory image or message is displayed briefly before the real page is loaded.

Note that this header is commonly set indirectly by putting

   CONTENT="5; URL=http://host/path/">

in the HEAD section of the HTML page, rather than as an explicit header from the server. That usage came about because automatic reloading or forwarding is something often desired by authors of static HTML pages. For servlets, however, setting the header directly is easier and clearer.

This header is not officially part of HTTP 1.1 but is an extension supported by both Netscape and Internet Explorer.


This header can be used in conjunction with a 503 (Service Unavail_able) response to tell the client how soon it can repeat its request.


The Set-Cookie header specifies a cookie associated with the page. Each cookie requires a separate Set-Cookie header. Servlets should not use response.setHeader("Set-Cookie", ...) but instead should use the special-purpose addCookie method of HttpServletResponse. For details, see Section 2.9 (Cookies). Technically, Set-Cookie is not part of HTTP 1.1. It was originally a Netscape extension but is now widely supported, including in both Netscape and Internet Explorer.


This header is always included with a 401 (Unauthorized) status code. It tells the browser what authorization type (BASIC or DIGEST) and realm the client should supply in its Authorization header. See Chapters 7 and 8 for a discussion of the various security mechanisms available to servlets.

  • + Share This
  • 🔖 Save To Your Account