📜  Servlet – 自动页面刷新

📅  最后修改于: 2022-05-13 01:54:27.729000             🧑  作者: Mango

Servlet – 自动页面刷新

servlet 组件中的 public service(HttpServletRequest req, HttpServletResponse res) 方法应该扩展 HttpServlet (AC)。它允许浏览器在经过一定时间后刷新网页。可以通过两种方式启用自动刷新:

  1. setHeader(“刷新”,字符串“”)
  2. setIntHeader(“刷新”, int )

“刷新”在这些方法中是固定的。时间作为字符串传递给 setHeader() 方法,而时间作为 int 数字传递给 setIntHeader() 方法。时间应该表示为几分之一秒。

例子:

setIntHeader("Refresh", 5);

自动页面刷新示例

这是页面刷新。我们编写页面刷新逻辑代码的Java文件

Java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
  
public class PageRefresh extends HttpServlet
{
     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
     {
          // Set refresh time as 1 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();
        
          out.println("

Auto Refresh Page

");           out.println("

Current time: "+CT+"

");      }      // Handle POST method request.      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException      {           doGet(request, response);      } }


XML

 
     PageRefresh
     PageRefresh
 
   
 
     PageRefresh
     /PageRefresh
 


以下是 web.xml 文件:

XML


 
     PageRefresh
     PageRefresh
 
   
 
     PageRefresh
     /PageRefresh
 

输出:

它每五秒刷新一次浏览器,当前时间将自动更改。