JSP auto refresh

Imagine how to achieve live scores, or real-time status of the stock market, or current foreign exchange ratios? Obviously, to implement this real-time feature, you have to refresh the page regularly.

JSP provides a mechanism to make this kind of work simple, it can automatically refresh the page periodically.

The easiest way to refresh a page is to use the setIntHeader() method of the response object. The signature of this method is as follows:

public  Void setIntHeader(String header, int headerValue)

This method tells the browser to refresh after a given time, in seconds.

Page auto-refresh program example

This example uses the setIntHeader() method to set the refresh header to simulate a digital clock:

<%@ page language="java" contentType="text/html; charset=UTF-8"
<%@ page import="java.io.*,java.util.*" %>
<title>Auto refresh instance</title>

<h2>Automatic refresh</h2>
   // Set to refresh every 5 seconds
   response.setIntHeader("Refresh", 5);
   // Get current time
   Calendar calendar = new GregorianCalendar();
   String am_pm;
   int hour = calendar.get(Calendar.HOUR);
   int minute = calendar.get(Calendar.MINUTE);
   int second = calendar.get(Calendar.SECOND);
   if(calendar.get(Calendar.AM_PM) == 0)
      am_pm = "AM";
      am_pm = "PM";
   String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
   out.println("Current time is: " + CT + "\n");


Save the above code in the main.jsp file and access it. It refreshes the page every 5 seconds and gets the current time of the system. The results are as follows:

Automatically refreshing

The current time is: 6:5:36 PM

You can also write a more complicated program yourself.