JSP 自动刷新

response 的 Refresh 头、meta refresh、定时跳转与轮询取舍。

Beginner
Key PointsRefresh 头让浏览器 N 秒后重新加载或跳转;它是最原始的轮询,现代页面多用 AJAX 局部更新。

Refresh 响应头

JSP
<%@ page contentType="text/html;charset=UTF-8" %>
<%
    response.setHeader("Refresh", "5");                    // 5 秒后刷新本页
    // response.setHeader("Refresh", "3;URL=done.jsp");     // 3 秒后跳转
%>
<!DOCTYPE html><html><body>
<h1>数据加载中,5 秒后自动刷新…</h1>
</body></html>

meta refresh

JSP
<head>
  <meta http-equiv="refresh" content="5">
  <%-- 跳转版:<meta http-equiv="refresh" content="3;url=done.jsp"> --%>
</head>

The header starts the countdown when the response arrives; the meta tag waits until parsing reaches it. For a "processing" page the header is more reliable; static pages can only use meta.

带倒计时

JSP
<%
    response.setHeader("Refresh", "3;URL=list.jsp");
%>
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>跳转中</title></head>
<body>
<h1>保存成功,<span id="n">3</span> 秒后返回列表</h1>
<script>
  let n = 3;
  setInterval(() => {
    n = Math.max(0, n - 1);
    document.getElementById('n').textContent = n;
  }, 1000);
</script>
</body></html>
Output
保存成功,3 秒后返回列表
(每秒递减,到 0 时页面自动跳到 list.jsp)

该用哪种

ApproachBest forCost
Refresh header整页重载的状态页整页重传、闪烁
meta refresh静态页、简单跳转同上
AJAX polling局部更新请求频繁
SSE / WebSocket服务端主动推送长连接占资源
A full refresh loses scroll position and unsubmitted input. A page refreshing while the user types is a genuinely bad experience — never auto-refresh a page with inputs.

轮询示例

JSP
<div id="status">处理中…</div>
<script>
  const timer = setInterval(async () => {
    const r = await fetch('status.jsp?id=${param.id}');
    const t = await r.text();
    document.getElementById('status').textContent = t;
    if (t === 'DONE') clearInterval(timer);
  }, 2000);
</script>

Partial polling updates one region while the rest of the page stays put — scroll and input preserved. Much better than a full reload, at the cost of a few lines of JavaScript.

Friends & Partners