考虑一个网页,这是显示现场游戏得分或股票的市场状况或货币汇率定量的。对于所有这些类型的页面,你需要浏览器刷新网页,定期使用referesh或重新加载“按钮。
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 - by www.gitbook.net 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 http://localhost:8080/Refresh这将显示当前的系统时间为每5秒后调用这个servlet的。只要运行servlet看到的结果如下:
Auto Page Refresh using ServletCurrent Time is: 9:44:50 PM |