Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

คุณสมบัติ Auto Refresh ใน JSP คืออะไร?

Auto Refresh ทำให้หน้าเว็บโหลดใหม่อัตโนมัติทุกช่วงเวลาที่กำหนด

การทำงาน

ใช้ response.setIntHeader("Refresh", seconds) ส่ง HTTP header:

Refresh: 5

Browser จะ reload หน้าทุก 5 วินาที

ตัวอย่าง: นาฬิกา Auto Refresh

<%@ page import="java.io.*,java.util.*" %>
<html>
<head><title>Auto Refresh</title></head>
<body>
    <center>
        <h2>Auto Refresh Example</h2>
        <%
            response.setIntHeader("Refresh", 5);
            Calendar cal = Calendar.getInstance();
            String time = cal.get(Calendar.HOUR) + ":" + 
                          cal.get(Calendar.MINUTE) + ":" + 
                          cal.get(Calendar.SECOND) + " " +
                          (cal.get(Calendar.AM_PM) == 0 ? "AM" : "PM");
            out.println("Current Time: " + time);
        %>
    </center>
</body>
</html>

ผลลัพธ์

Auto Refresh Header Example
Current Time is: 9:44:50 PM

วิธีทางเลือก: Meta Tag

<meta http-equiv="refresh" content="5">

วางใน <head> ทำงานเหมือนกัน แต่เป็น client-side only

ข้อจำกัดและแนวทางปัจจุบัน

  • Server-sent header: ควบคุมได้จาก server-side logic
  • Meta tag: static, ไม่ dynamic ได้
  • ทั้งสอง: reload ทั้งหน้า (full page reload) - UX ไม่ดี
  • แนะนำ: ใช้ AJAX/Fetch polling หรือ WebSocket/SSE สำหรับ real-time updates

กรณีใช้งานที่เหมาะสม

  • Dashboard monitoring (server status, metrics)
  • Simple status pages
  • Legacy systems ที่ไม่รองรับ AJAX