📜  Servlet-自动页面刷新

📅  最后修改于: 2020-11-12 05:44:40             🧑  作者: Mango


考虑一个显示实时游戏得分或股票市场状态或货币汇率的网页。对于所有此类页面,您将需要使用浏览器的“刷新”或“重新加载”按钮定期刷新网页。

Java Servlet通过为您提供一种机制来简化此工作,使您可以以某种方式制作网页,使其在给定间隔后自动刷新。

刷新网页的最简单方法是使用响应对象的setIntHeader()方法。以下是此方法的签名-

public void setIntHeader(String header, int headerValue)

此方法将标头“ Refresh”连同指示时间间隔(以秒为单位)的整数一起发送回浏览器。

自动页面刷新示例

此示例显示servlet如何使用setIntHeader()方法设置Refresh标头来执行自动页面刷新。

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
 
// Extend HttpServlet class
public class Refresh extends HttpServlet {
 
   // Method to handle GET method request.
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      // Set refresh, autoload time as 5 seconds
      response.setIntHeader("Refresh", 5);
 
      // Set response content type
      response.setContentType("text/html");
 
      // 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;
    
      PrintWriter out = response.getWriter();
      String title = "Auto Page Refresh using Servlet";
      String docType =
         ""-//w3c//dtd html 4.0 " + "transitional//en\">\n";
      
      out.println(docType +
         "\n" +
         "" + title + "\n"+
         "\n" +
         "

" + title + "

\n" + "

Current Time is: " + CT + "

\n" ); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

现在让我们编译上面的servlet并在web.xml中创建以下条目

....
 
     Refresh
     Refresh
 
 
 
     Refresh
     /Refresh
 
....

现在,使用URL http:// localhost:8080 / Refresh调用此servlet,它每5秒显示一次当前系统时间,如下所示。只需运行servlet并等待查看结果-

Auto Page Refresh using Servlet
Current Time is: 9:44:50 PM