JSP 預設 response.sendRedirect() 為 302,若需 301 必須手動設定狀態碼與 Location 標頭。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%
// 設定狀態碼為 301
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
// 設定新位置(建議使用絕對路徑或完整 URL)
response.setHeader("Location", "/other.jsp");
// 結束輸出,避免後續內容干擾
return;
%>
HttpServletResponse.SC_MOVED_PERMANENTLY 常數值為 301,語意清晰不易出錯。Location 標頭值可為相對路徑(如 /other.jsp)或完整 URL(如 https://example.com/new-page)。return; 立即結束 JSP 執行,防止後續程式碼輸出內容導致「標頭已送出」錯誤。response.setHeader("Location", "/other.jsp?id=123");<% response.sendRedirect("/temp-page.jsp"); %>
// 等同於
<%
response.setStatus(HttpServletResponse.SC_FOUND); // 302
response.setHeader("Location", "/temp-page.jsp");
%>