考慮一個網頁,這是顯示現場遊戲得分或股票的市場狀況或貨幣彙率定量的。對於所有這些類型的頁麵,你需要瀏覽器刷新網頁,定期使用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 |