通過響應頭重定向
響應狀態 301 和 302 可以指定重定向URL, 推薦使用302 FOUND
HttpServletResponse. static final int SC_MOVED_TEMPORARILY
狀態代碼(302),指示資源已臨時移動到另一個位置,但未來的引用仍應使用原始URI來訪問資源。 保留此定義是為了向后兼容。 SC_FOUND現在是首選定義。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<%
/* 重定位狀態分兩種:
永久301 Moved Permanently和暫時302 Found
謹慎使用永久轉移
*/
//response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setStatus(HttpServletResponse.SC_FOUND);
response.setHeader("Location", "indexs.jsp");
%>
通過元數據 meta 跳轉頁面
該方式可向用戶顯示提示信息, 推薦使用
注意, 如果refresh間隔時間太短或太長都會對用戶造成困擾
<!DOCTYPE HTML>
<html lang="zh">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 3秒后跳轉頁面 -->
<meta http-equiv="refresh" content="2;url='https://www.google.com'">
<title>3秒后進入主題</title>
<link rel="icon" href="icon/icon.ico">
<link rel="stylesheet" href="css/global.css">
<body>
<p style="text-align: center;">
<a href="https://www.google.com">點擊立即進入</a>
</p>
</body>
</html>
事件 + JS 實現跳轉
向 window 添加 onload 事件監聽, 並重定位 document.location 到新的頁面
該方法靈活性較高
- 立即跳轉
在棧中不會有跳轉頁面
<script>
window.addEventListener("load", function (){
(window/document).location.(href) = "/speedtest"
});
</script>
<!-- 事實上這是多余的, 並且每個瀏覽器行為不一致, 可直接跳轉 -->
<script>
document.location = "/speedtest"
</script>
- 延遲跳轉
堆棧會留下跳轉頁面, 停留1s最佳
<script>
setTimeout(function () {
document.location = "/"
}, 1000)
</script>