Imagine if you want to live broadcast the score of the game, or the real-time status of the stock market, or the current foreign exchange rationing, how to achieve it? Obviously, to achieve this real-time functionality, you have to refresh the page regularly.
JSP provides a mechanism to make this work easy, which can automatically refresh the page regularly.
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 tells the browser to refresh after a given amount of time, measured in seconds.
This example uses the setIntHeader() method to set the refresh header, simulating 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 main.jsp file and access it. It will refresh the page every 5 seconds and get the current system time. The running results are as follows:
Auto Refresh Header ExampleCurrent Time is: 9:44:50 PMYou can also write a more complex program yourself.