Auto Page Refresh Servlets with setHeader()

What is Page Refresh Servlets?

Sometimes, user requires latest information on Cricket score or latest Share prices etc. where he is required to refresh the page, say by typing F5 key. To make user’s job easier, Servlet comes with setHeader("refresh", "5") method. With this method, the same Servlet is called for every 5 seconds once and displays the latest time. This is called Page Refresh Servlets.

Let us see what API says about this method

public void setHeader(String header, String time)

Example on Page Refresh Servlets

Client file: UseRefresh.html

  Call servlet with auto refresh example.

Servlet file:

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Date;

public class DisplayRefreshTime extends HttpServlet
  public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

    response.setHeader("refresh", "5");

    PrintWriter out = response.getWriter();
    out.println("Observe, the following time refreshes for each 5 seconds once.");

    Date d = new Date();

Hours: " + d.getHours() +"
Minutes: " + d.getMinutes() + "
Seconds: " + d.getSeconds()+"
"); out.close(); } }

web.xml Entry



response.setHeader("refresh", "5");

setHeader() reloads the same Servlet, DisplayRefreshtime, for each 5 seconds once and refreshes the time.

The above Servlet header is equivalent to HTMl <meta> tag.

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

Also try with

response.setIntHeader("refresh", 5);

Here, the second parameter is an integer value (earlier it was string).

Client HTML Screen: UseRefresh.html


Servlet screen, DisplayRefreshTime, when hyper link is clicked

Output screen of Page Refresh Servlets

Leave a Comment

Your email address will not be published.