JSP Auto Refresh
Imagine if you want to live broadcast match scores, the real-time status of the stock market, or the current foreign exchange rates, how would you implement it? Obviously, to achieve such real-time functionality, you have to refresh the page regularly.
JSP provides a mechanism to make this work easy; it can automatically refresh the page on a timed basis.
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.
Page Auto Refresh Program Example
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>自动刷新实例</title>
</head>
<body>
<h2>自动刷新实</h2>
<%
// 设置每隔5秒刷新一次
response.setIntHeader("Refresh", 5);
// 获取当前时间
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("当前时间为: " + CT + "\n");
%>
</body>
</html>
Save the above code in the main.jsp file and access it. It will refresh the page every 5 seconds and obtain the system's current time. The results are as follows:
自动刷新实 当前时间为: 6:5:36 PM
You can also write a more complex program yourself.
Other Extensions