登入成功、操作完成、錯誤提示等頁面,需顯示倒數秒數並自動跳轉至目標頁(如登入首頁)。
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title>操作成功 - 即將跳轉</title>
<style>
body { font-family: sans-serif; text-align: center; padding-top: 100px; }
#countdown { color: #e74c3c; font-size: 24px; font-weight: bold; }
</style>
</head>
<body onload="startCountdown()">
<h2>操作成功!</h2>
<p><span id="countdown">5</span> 秒後自動跳轉登入頁面...</p>
<p>若未自動跳轉,請點擊 <a href="<%= request.getContextPath() %>/login.jsp">這裡</a> 手動跳轉。</p>
<script>
var seconds = 5;
var targetUrl = "<%= request.getContextPath() %>/login.jsp";
function startCountdown() {
var el = document.getElementById('countdown');
var timer = setInterval(function() {
seconds--;
el.textContent = seconds;
if (seconds <= 0) {
clearInterval(timer);
window.location.href = targetUrl;
}
}, 1000);
}
</script>
</body>
</html>
<body onload="startCountdown()">:頁面載入完成啟動倒數。setInterval 每秒遞減秒數並更新 DOM。window.location.href 執行實際跳轉(替換歷史記錄,無法回退)。<meta http-equiv="refresh" content="5;url=<%= request.getContextPath() %>/login.jsp">
優點: 相容性極高,無需 JS。
缺點: 無法顯示動態倒數秒數,使用者體較差;部分瀏覽器安全設定可能阻擋。
function autoRedirect(options) {
var opts = Object.assign({
seconds: 5,
url: '/',
message: '秒後自動跳轉...',
selector: '#countdown'
}, options);
var el = document.querySelector(opts.selector);
if (!el) return;
var timer = setInterval(function() {
opts.seconds--;
el.textContent = opts.seconds;
if (opts.seconds <= 0) {
clearInterval(timer);
window.location.href = opts.url;
}
}, 1000);
}
// 使用範例
autoRedirect({
seconds: 3,
url: '${pageContext.request.contextPath}/dashboard.jsp',
selector: '#timer'
});
location.href,體驗最佳。${pageContext.request.contextPath} 或 <%= request.getContextPath() %> 動態生成,避免硬編碼路徑。aria-live="polite" 讓螢幕閱讀器朗讀倒數。