JSP Auto Refresh
Imagine if you need to live broadcast the score of a game, the real-time status of the stock market, or the current foreign exchange allocation, how would you achieve this? Clearly, to implement such real-time functionality, you would have to regularly refresh the page.
JSP provides a mechanism to make this task simpler, allowing the page to refresh automatically at set intervals.
The simplest 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 informs the browser to refresh after a given time, measured in seconds.
Example of an Auto Refresh Program
This example uses the setIntHeader()
method to set the refresh header, simulating a digital clock:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Auto Refresh Example</title>
</head>
<body>
<h2>Auto Refresh Example</h2>
<%
// Set to refresh every 5 seconds
response.setIntHeader("Refresh", 5);
// Get the 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";
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
out.println("Current Time is: " + CT + "\n");
%>
</body>
</html>
Save the above code in a file named main.jsp
and access it. It will refresh the page every 5 seconds and fetch the current system time. The output will look like this:
Auto Refresh Example
Current Time is: 6:5:36 PM
You can also write a more complex program on your own.