May 12, 2021 JSP
Imagine if you wanted to live-stream the score of a game, or the real-time state of the stock market, or the current forex rations. Obviously, to achieve this real-time functionality, you have to refresh the page regularly.
JSP provides a mechanism to make this easier by automatically refreshing pages on a timed basis.
The easiest way to refresh a page is to use the setIntHeader() method of the response object. T he 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, in seconds.
This example uses the setIntHeader() method to set the refresh header to simulate a digital clock:
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Auto Refresh Header Example</title>
</head>
<body>
<center>
<h2>Auto Refresh Header Example</h2>
<%
// Set refresh, autoload time as 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";
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
out.println("Crrent Time: " + CT + "\n");
%>
</center>
</body>
</html>
Save the above code in the .jsp file and access it. I t refreshes the page every 5 seconds and gets the system's current time. The results are as follows:
Auto Refresh Header Example Current Time is: 9:44:50 PM
You can also write a more complex program yourself.