Servlet automatically refreshes the page
Suppose there is a web page that displays live game results or stock market conditions or currency exchange rates. For all these types of pages, you need to refresh the web page regularly.
Java Servlet provides a mechanism so that the web page will automatically refresh at a given time interval.
The simplest way to refresh a web page is to use the response object method setIntHeader(). The following is the definition of this method:
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).
Automatic refresh page example
This example demonstrates how Servlet uses the setIntHeader() method to set the Refresh header information to achieve Automatically refresh the page.
// 导入必需的 java 库 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // 扩展 HttpServlet 类 public class Refresh extends HttpServlet { // 处理 GET 方法请求的方法 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置刷新自动加载的事件间隔为 5 秒 response.setIntHeader("Refresh", 5); // 设置响应内容类型 response.setContentType("text/html"); // 获取当前的时间 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 public \"-//w3c//dtd html 4.0 " + "transitional//en\">\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"); } // 处理 POST 方法请求的方法 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Now let us compile the above Servlet and create the following entry in the web.xml file:
.... <servlet> <servlet-name>Refresh</servlet-name> <servlet-class>Refresh</servlet-class> </servlet> <servlet-mapping> <servlet-name>Refresh</servlet-name> <url-pattern>/Refresh</url-pattern> </servlet-mapping> ....
Now call this by accessing the URL http://localhost:8080/Refresh Servlets. This will display the current system time every 5 seconds. Run the Servlet and wait to see the results:
Use Servlet to automatically refresh the pageThe current time is: 9:44:50 PM |