Home > Articles > Programming > Java

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.

Allow

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.

Cache-Control

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.

Connection

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.

Content-Encoding

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.

Content-Language

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/).

Content-Length

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.

Content-Type

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

Type

Meaning

application/msword

Microsoft Word document

application/octet-stream

Unrecognized or binary data

application/pdf

Acrobat (.pdf) file

application/postscript

PostScript file

application/vnd.lotus-notes

Lotus Notes file

application/vnd.ms-excel

Excel spreadsheet

application/vnd.ms-powerpoint

PowerPoint presentation

application/x-gzip

Gzip archive

application/x-java-archive

JAR file

application/x-java-serialized-object

Serialized Java object

application/x-java-vm

Java bytecode (.class) file

application/zip

Zip archive

audio/basic

Sound file in .au or .snd format

Type

Meaning

audio/midi

MIDI sound file

audio/x-aiff

AIFF sound file

audio/x-wav

Microsoft Windows sound file

image/gif

GIF image

image/jpeg

JPEG image

image/png

PNG image

image/tiff

TIFF image

image/x-xbitmap

X Windows bitmap image

text/css

HTML cascading style sheet

text/html

HTML document

text/plain

Plain text

text/xml

XML

video/mpeg

MPEG video clip

video/quicktime

QuickTime video clip


Expires

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.

Last-Modified

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.

Location

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).

Pragma

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.

Refresh

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

<META HTTP-EQUIV="Refresh" 
   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.

Retry-After

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.

Set-Cookie

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.

WWW-Authenticate

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020