SpringMVC 的頁面跳轉方案主要分為 ?轉發(Forward)?
和 ?重定向(Redirect)?
兩類,具體實現方式和區別如下:
一、頁面跳轉方案
1. ?轉發(Forward)?
- 默認方式?:直接返回字符串邏輯視圖名,由視圖解析器拼接前綴和后綴生成完整路徑。
@RequestMapping("/example")
public String example(Model model) {model.addAttribute("data", "value");return "viewName"; // 默認轉發到 /WEB-INF/views/viewName.jsp
}
- 顯式轉發?:通過 forward: 關鍵字指定目標地址,?不經過視圖解析器?。
return "forward:/targetPath"; // 轉發到指定路徑(頁面或另一個 Controller)
2. ?重定向(Redirect)?
- 顯式重定向?:通過 redirect: 關鍵字指定目標地址,?不經過視圖解析器?,且地址欄會變化。
Copy Code
return "redirect:/targetPath"; // 重定向到指定路徑(頁面或另一個 Controller)
- 帶參數重定向?:通過 RedirectAttributes 傳遞參數。
@RequestMapping("/save")
public String save(RedirectAttributes attributes) {attributes.addAttribute("param", "value"); // URL 參數attributes.addFlashAttribute("flashParam", "value"); // 臨時存儲return "redirect:/targetPath";
}
二、轉發與重定向的區別
特性? | 轉發(Forward)? | 重定向(Redirect)? |
---|---|---|
地址欄變化? | 不變化(服務器內部跳轉)? | 變化(客戶端重新發起請求)? |
請求次數? | 1 次請求 | 2 次請求 |
?數據共享? | 可通過 Model 或 request 共享數據? | 需通過 URL 參數或 RedirectAttributes? |
?視圖解析器生效范圍? | 默認方式生效,顯式轉發不生效? | 顯式重定向不生效? |
應用場景? | 需要保留請求上下文(如表單提交后回顯數據) | 需防止重復提交(如支付成功后跳轉結果頁) |
三、擴展場景示例
1?. 跳轉到其他 Controller?
// 轉發到其他 Controller
return "forward:/otherController/method";// 重定向到其他 Controller
return "redirect:/otherController/method";
?2. 靜態資源跳轉?
重定向可直接跳轉到外部資源或靜態頁面(如 redirect:http://example.com
),而轉發僅限服務器內部資源?78。
總結
SpringMVC 的跳轉方案以轉發和重定向為核心,通過 forward: 和 redirect: 關鍵字實現靈活控制。選擇方案時需結合地址欄變化、數據傳遞需求和安全性等因素?14。