Servlet Auto-Refresh Page
Suppose there is a web page that displays live game scores, stock market conditions, or currency exchange rates. For all these types of pages, you need to refresh the page periodically.
Java Servlet provides a mechanism that makes a web page refresh automatically at a given time interval.
The simplest way to refresh a web page is to use the response object's method setIntHeader(). The definition of this method is as follows:
public void setIntHeader(String header, int headerValue)
This method sends the header "Refresh" back to the browser along with an integer value representing the time interval (in seconds).
Auto-Refresh Page Example
This example demonstrates how a Servlet uses the setIntHeader() method to set the Refresh header, thereby achieving automatic page refresh.
package com.runoob.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;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Set the interval for automatic refresh loading to 5 seconds
response.setIntHeader("Refresh", 5);
// Set response content type
response.setContentType("text/html;charset=UTF-8");
// 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;
PrintWriter out = response.getWriter();
String title = "Automatically Refreshing a Page Using Servlet";
String docType = " \n";
out.println(docType +
"\n" +
"" + title + " \n"+
"\n" +
"" + title + "
\n" +
"当前时间是:" + CT + "
\n");
}
}
Now let's compile the above Servlet and create the following entry in the web.xml file:
Refresh
com.runoob.test.Refresh
Refresh
/TomcatTest/Refresh
Now invoke this Servlet by visiting http://localhost:8080/TomcatTest/Refresh. This will display the current system time every 5 seconds. Run the Servlet and wait to see the result:
Use a Servlet to Auto-Refresh a PageCurrent time is: 9:44:50 PM |
|---|