在 SpringMVC 中,可以指定畫面的跳轉方式。使用 forward:
前綴實現請求轉發跳轉,使用 redirect:
前綴實現重定向跳轉。有前綴的轉發和重定向操作和配置的視圖解析器沒有關系,視圖解析器不會進行拼串。
請求轉發前綴—forward:
使用請求轉發跳轉方式,url 地址不會改變,一次請求一次相應,跳轉到的地址可以獲得 request 中的數據。
/**
* 請求轉發
*/
@RequestMapping("/hello")
public String hello(HttpServletRequest request){
// 跳轉到的地址能獲得 name 中的值
request.setAttribute("name", "jack");
// 當前項目下的 hello.jsp 頁面,請區別配置視圖解析器的返回值,這里不會進行拼串
return "forward:/hello.jsp";
}
重定向前綴—redirect:
使用重定向跳轉方式,url 地址會改變,兩次請求兩次相應,跳轉到的地址不可以獲得 request 中的數據(因為是兩次請求)。
/**
* 重定向
*/
@RequestMapping("/hello")
public String hello(HttpServletRequest request){
// 跳轉到的地址無法獲得 name 中的值
request.setAttribute("name", "jack");
// 不需要添加當前的項目名,SpringMVC會自動的添加項目名
return "redirect:/hello.jsp";
}
由於重定向方式無法傳遞參數,解決方法請參考 RedirectAttributes 這一章節。