Setting response headers

  1. Server sends the response headers which contains configuration information of the Server and data about response. like content type ,content-length etc.
  2. Browser uses these response headers to display information property to the end user.

HttpservletResponse defines the following methods to set response headers.

    public void setHeader(String hname,String hvalue)
    public void addHeader(String hname,String hvalue)

public void setHeader(String hname,String hvalue)

  1. If the specified header is already available then the old value is replaced with new value.
  2. If it is not already available then as a new entry it will be added.

public void addHeader(String hname,String hvalue)
If the specified header is already available, to the existing values provided value also will be added without replacement.

HttpServletResponse also defines the following more convient methods to add int and date headers.

  1. public void addIntHeader(String hname,int value)
  2. public void setIntHeader(String hname,int value)
  3. public void addDateHeader(String hname,long ms)
  4. public void setDateHeader(String hname, long ms)

Setting content type of response

content type response header represents MIME type of response document.(MIME->multipurpose internet mail extension)

Common MIME types

  1. text/html ->HTML document as response.
  2. text/xml ->XML document
  3. application/pdf ->pdf file
  4. images/jpeg -> JPEG image file

we can set content type in one of the following possibilities.

  1. By ServletResponse

    public void setcontentType(String mime).
    Example:resp.setContentType(“application/pdf”);

  2. By HttpServletResponse

    public void setHeader(“content-Type”,”text/html”);
    Example:resp.setHeader(“content-Type”,”text/html”);