在 Servlet/JSP 中,通過 HttpServletResponse 發送重導向指令,告知瀏覽器訪問新 URL。301 (Moved Permanently) 和 302 (Found) 是最常用的兩種狀態碼,語義與 SEO 影響不同。
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); // 301
response.setHeader("Location", "https://www.example.com/new-url");
// 必須調用 flush 或返回,防止後續代碼繼續輸出內容
return;
// 內部實現:setStatus(302) + setHeader("Location", url)
response.sendRedirect("https://www.example.com/new-url");
return;
// Servlet 3.1 (Java EE 7) 新增
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.sendRedirect("https://www.example.com/new-url");
| 特性 | 301 Moved Permanently | 302 Found (Temporary Redirect) |
|---|---|---|
| 語義 | 資源永久移動到新位置 | 資源臨時在新位置 |
| SEO 權重傳遞 | 傳遞頁面權重 (PageRank) 給新 URL | 不傳遞權重,搜索引擎保留舊 URL 索引 |
| 瀏覽器緩存 | 瀏覽器會緩存重導向,下次直接訪問新 URL | 不緩存,每次請求舊 URL |
| 適用場景 | 域名遷移、HTTPS 強制跳轉、URL 結構永久調整 | 登錄後跳轉、臨時維護頁面、A/B 測試 |
HttpServletResponse.SC_MOVED_PERMANENTLY (301) 和 SC_FOUND (302) 避免魔術數字。return,防止響應體被污染。return "redirect:/new-url" (302) 或 RedirectView 設置 setStatusCode(HttpStatus.MOVED_PERMANENTLY) (301)。