一、RedirectAttributes類簡介
- RedirectAttributes是Spring mvc 3.1版本之後出來的一個功能,專門用於重定向之後還能帶參數跳轉的工具類
- 使用此類引入包:import org.springframework.web.servlet.mvc.support.RedirectAttributes;
- 劃重點:用於重定向攜帶參數
二、類中常用方法介紹
-
addAttributie方法
redirectAttributes.addAttributie("param1",value1); redirectAttributes.addAttributie("param2",value2); return "redirect:/path/list" ;
注意:這個方法是用來跳轉的時候,將參數直接暴露在url中,等同於重定向到:return "redirect:/path/list?prama1=value1¶m2=value2 "
-
addFlashAttributie方法
redirectAttributes.addFlashAttributie("prama1",value1); redirectAttributes.addFlashAttributie("prama2",value2); return:"redirect:/path/list.jsp" ;
注意:此方法是重定向的時候,param1和param2兩個參數在不暴露在url中隱藏的傳遞給list.jsp中
原理:其原理就是放到session中,session在跳到頁面後馬上移除對象。 - 以上兩種方法只能將參數重定向到頁面中,也就是視圖中用el表達式直接獲取你帶參的值,不能重定向到controller中獲取參數值
-
如果想要在controller中獲取傳遞到參數的值:
- 對於addAttributie方法傳遞的值使用@RequestParam("param1") String str 來獲取; - 對於addFlashAttribute方法傳遞的值使用@ModelAttribute("param1") String str 來獲取;