runoops.com

Servlet 自动刷新页面

假设有一个网页,它是显示现场比赛成绩或股票市场状况或货币兑换率。对于所有这些类型的页面,您需要定期刷新网页。

Java Servlet 提供了一个机制,使得网页会在给定的时间间隔自动刷新。

刷新网页的最简单的方式是使用响应对象的方法 setIntHeader()。以下是这种方法的定义:

public void setIntHeader(String header, int headerValue)

此方法把头信息 "Refresh" 连同一个表示时间间隔的整数值(以秒为单位)发送回浏览器。

自动刷新页面实例

本实例演示了 Servlet 如何使用 setIntHeader() 方法来设置 Refresh 头信息,从而实现自动刷新页面。

实例

package com.runoops.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;

import java.util.GregorianCalendar;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Refresh
 */
@WebServlet("/Refresh")
public class Refresh extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Refresh() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 设置刷新自动加载的事件间隔为 5 秒
        response.setIntHeader("Refresh", 5);
     
        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");
     
        // 获取当前的时间
        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;
        
        PrintWriter out = response.getWriter();
        String title = "使用 Servlet 自动刷新页面";
        String docType = "<!DOCTYPE html> \n";
        out.println(docType +
            "<html>\n" +
            "<head><title>" + title + "</title></head>\n"+
            "<body bgcolor=\"#f0f0f0\">\n" +
            "<p align=\"center\">" + title + "</p>\n" +
            "<p align=\"center\">当前时间是:" + CT + "</p>\n");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

现在让我们来编译上面的 Servlet,现在通过访问 http://localhost:8089/ServletTest/Refresh 来调用这个 Servlet。这将会每隔 5 秒钟显示一次当前系统时间。运行该 Servlet,并等待查看结果: