HTTP 報頭設定例項、響應及總結
阿新 • • 發佈:2018-12-27
eg:
@WebServlet("/Refresh") public class Refresh extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub //super.doGet(req, resp); // 設定重新整理自動載入時間為 5 秒 //Refresh:這個頭資訊指定瀏覽器應該如何儘快請求更新的頁面。您可以指定頁面重新整理的秒數。 resp.setIntHeader("Refresh", 500); System.out.println("req:"+req); System.out.println("resp:"+resp); resp.setContentType("text/html;charset=UTF-8"); Calendar calendar=Calendar.getInstance(); java.util.Date taskTime=calendar.getTime(); SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //格式化輸出 String nowTime = df.format(taskTime); PrintWriter out = resp.getWriter(); String title = "自動重新整理 Header 設定 - 菜鳥教程例項"; String docType = "<!DOCTYPE html>\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n"+ "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<p>當前時間是:" + nowTime + "</p>\n"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub //super.doPost(req, resp); doGet(req, resp); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub super.service(req, resp); } }
效果:每隔500秒瀏覽器頁面重新整理一次,並顯示當前時間。
總結:當瀏覽器第一次向伺服器發請求的時候,伺服器為請求設定請求頭資訊,
resp.setIntHeader("Refresh", 500);(本例中)
然後瀏覽器解析請求頭並作出相應的反饋。伺服器不會主動向瀏覽器發訊息,只有當瀏覽器請求的時候伺服器才會作出反饋。