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

  • setHeader(String headerName, String headerValue)

    This method sets the response header with the designated name to the given value.

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. The methods 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(String mimeType)

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

  • setContentLength(int length)

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

  • addCookie(Cookie c)

    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 Chapter 8 (Handling Cookies) for a discussion of cookies.

  • sendRedirect(String address)

    As discussed in the previous chapter, the sendRedirect method sets the Location header as well as setting the status code to 302. See Sections 6.3 (A Servlet That Redirects Users to Browser-Specific Pages) and 6.4 (A Front End to Various Search Engines) for examples.

Core Servlets and JavaServer Pages (Vol. 1.Core Technologies)
Core Servlets and Javaserver Pages: Core Technologies, Vol. 1 (2nd Edition)
ISBN: 0130092290
EAN: 2147483647
Year: 2002
Pages: 194

Similar book on Amazon

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