English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Imagine, if you want to live broadcast the score of a match, or the real-time status of the stock market, or the current foreign exchange allocation, how can you achieve this? Clearly, to implement this real-time function, you have to refresh the page regularly.
JSP provides a mechanism to make this task easier, allowing the page to refresh automatically at regular 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 notifies the browser to refresh after a given time, with the time in seconds.
This example uses the setIntHeader() method to set the refresh header and simulate 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</h2> <% // Set every5seconds refresh 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 the main.jsp file and access it. It will refresh every5seconds refresh the page and get the current system time. The running result is as follows:
Auto Refresh Current time is: 6:5:36 PM
You can also write a more complex program yourself.