Categories: JSP 教程

JSP 自动刷新


JSP 自动刷新

想象一下,如果要直播比赛的比分,或股票市场的实时状态,或当前的外汇配给,该怎么实现呢?显然,要实现这种实时功能,您就不得不规律性地刷新页面。

JSP提供了一种机制来使这种工作变得简单,它能够定时地自动刷新页面。

刷新一个页面最简单的方式就是使用response对象的setIntHeader()方法。这个方法的签名如下:

public void setIntHeader(String header, int headerValue)

这个方法通知浏览器在给定的时间后刷新,时间以秒为单位。


页面自动刷新程序示例

这个例子使用了setIntHeader()方法来设置刷新头,模拟一个数字时钟:

<%@ 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 + "
"); 
%>
</center>
</body>
</html>

把以上代码保存在main.jsp文件中,访问它。它会每隔5秒钟刷新一次页面并获取系统当前时间。运行结果如下:

Auto Refresh Header Example
Current Time is: 9:44:50 PM

您也可以自己动手写个更复杂点的程序。

terry

这个人很懒,什么都没有留下~

Share
Published by
terry

Recent Posts

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

3 天 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

1 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

2 周 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

2 周 ago

聊聊React和Vue组件更新的实现及区别

React 和 Vue 都是当…

3 周 ago