Home Tutorial Servlet Java Servlet : Http Response Headers


Share on Google+Share on Google+
Java Servlet : Http Response Headers
Posted on: October 6, 2012 at 12:00 AM
In this tutorial, you will learn how to Http Response Headers works in java servlet.

Java Servlet : Http Response Headers

In this tutorial, you will learn how to Http Response Headers works in java servlet.

Http Response Headers :

Web server sends response with one or more response headers including the document content. You can use HTTP response headers to specify cookies, to instruct the browser to reload the page after a specified interval, setting content type, setting content length etc.

In general you can set header by using setHeader() method of HttpServletResponse.
setHeader(String headerName, String headerValue) : it sets the response header with specified name to the given value.
There is another method holds date and int - setDateHeader(String header, long milliseconds) and setIntHeader(String header, int headerValue).

Here are the list of some Http Response headers :

  • Content-Type : It shows the MIME type of the document
  • Content-Length : It Sets the length of the content body in the response
  • Refresh : to instruct the browser to reload the page after a specified interval
  • Set-Cookie : represent cookie associated with page

Example :

In this example we are using HttpResponse header and setting refresh rate of page 10 sec as -
response.setHeader("Refresh", "10")
This example displays date and time which is automatically refreshed after 10 sec.


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

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

public class HttpResponseHeaderExample extends HttpServlet {

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Date date = new Date();
PrintWriter out = response.getWriter();
out.println("<b>Current Date: </b>"+ date);
response.setHeader("Refresh", "10");


web.xml -

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">


Output :


Related Tags for Java Servlet : Http Response Headers:

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 6, 2012

Recommend the tutorial

Advertisements Advertisements