Servlet-自动页面刷新



考虑一个网页,它显示直播比赛分数或股票市场状态或货币兑换率。对于所有这类网页,你需要使用浏览器的刷新或重新加载按钮定期刷新你的网页。

Java Servlet通过向你提供一种机制,让你可以制作一个网页,它将按给定的时间间隔自动刷新,从而简化了这项工作。

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

public void setIntHeader(String header, int headerValue)

该方法将标头“刷新”发送回浏览器,同时附带一个整数值,该值指示所涉及的秒数。

自动页面刷新示例

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

// 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 =
         "<!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>Current Time is: " + CT + "</p>\n"
      );
   }
   
   // Method to handle POST method request.
   public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      doGet(request, response);
   }
}

现在让我们编译上述Servlet并在web.xml中创建以下条目

....
 <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>
....

现在使用URL https://127.0.0.1:8080/Refresh调用此Servlet,该URL将每隔5秒以当前系统时间显示。只要运行Servlet并等待查看结果 -

Auto Page Refresh using Servlet

Current Time is: 9:44:50 PM

广告