Auto Page Refresh Servlets with setHeader()

May 29, 2014 | Servlets
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

  <a href="http://localhost:8888/india/DRT">Call servlet with auto refresh example.</a>

Servlet file: DisplayRefreshTime.java

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

public class DisplayRefreshTime extends HttpServlet
{
  public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    response.setContentType("text/html");

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

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

    Date d = new Date();
    out.println("<br><br>Hours: " + d.getHours() +"<br>Minutes: " + d.getMinutes() +  "<br>Seconds:  " + d.getSeconds()+"</b>");

    out.close();
  }
}

web.xml Entry

<servlet>
  <servlet-name>klm</servlet-name>
  <servlet-class>DisplayRefreshTime</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>klm</servlet-name>
  <url-pattern>/DRT</url-pattern>
</servlet-mapping>

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

Also try with

response.setIntHeader("refresh", 5);

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

Client HTML Screen: UseRefresh.html

ima

Servlet screen, DisplayRefreshTime, when hyper link is clicked

ima1 Output screen of Page Refresh Servlets