How do I automatically refresh a servlet?
Author: Deron Eriksson
Description: This tutorial describes how to add a Refresh response header to refresh a servlet.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0) || Tomcat 5.5.20


There are a couple primary ways in which a servletW can be automatically refreshed. This tutorial shows both methods. One way is to add a "Refresh" response header containing the number of seconds after which a refresh should occur. The TestServlet class below shows an example of this.

TestServlet.java

package com.cakes;

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

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

public class TestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		performTask(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		performTask(request, response);
	}

	private void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		response.setContentType("text/html");
		response.addHeader("Refresh", "5");
		PrintWriter out = response.getWriter();
		out.println("TestServlet says hi at " + new Date());
	}

}

The response.addHeader("Refresh", "5") call adds a response header that is sent back to the client indicating that the browser should make another request of the servlet after 5 seconds.

test servlet

We can see that the browser refreshes every five seconds, as shown below.

test servlet refreshes every 5 seconds

A second way to perform a refresh is to include a meta refresh in the HTMLW sent to the client browser. The following meta refresh performs a refresh after 5 seconds.

	<meta http-equiv="refresh" content="5" />

In the following example, the client browser is redirected to www.google.com after 5 seconds.

	<meta http-equiv="refresh" content="5;url=http://www.google.com" />