Latest web development tutorials

Servlet page automatically refreshes

Suppose you have a website, it is to show a live game scores or stock market conditions or currency exchange rates. For all of these types of pages, you need to periodically refresh the page.

Java Servlet provides a mechanism so that the page will automatically refresh interval at a given time.

The easiest way to refresh the page is to use the response object's methodsetIntHeader ().The following is the definition of this method:

public void setIntHeader (String header, int headerValue)

This method head information "Refresh" integer value, together with a time interval (in seconds) to send back to the browser.

Automatic refresh the page instance

This example demonstrates how to use the ServletsetIntHeader () method to set the Refreshheader information to automatically refresh the page.

package com.w3big.test;

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
public class Refresh extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// 设置刷新自动加载的事件间隔为 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";
			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" +
	        "<h1 align=\"center\">" + title + "</h1>\n" +
	        "<p>当前时间是:" + CT + "</p>\n");


Now let's compile the above Servlet, and create the following entry in the web.xml file:

<?xml version="1.0" encoding="UTF-8"?>

Now by visiting http: to call the Servlet 8080 / TomcatTest / Refresh: // localhost. This will display once every 5 seconds, the current system time. Run the Servlet, and wait to see the results:

Use Servlet page automatically refreshes

Current time: 9: 44: 50 PM