SpringMVC中使用 RedirectAttributes 從一個(gè)controller重定向傳值(參數(shù))到另一個(gè)controller的方法:
介紹:RedirectAttributes是Spring mvc 3.1版本之后出來的一個(gè)功能,專門用于重定向之后還能帶參數(shù)跳轉(zhuǎn)的。
他有兩種帶參的方式:
? 第一種:
? attr.addAttribute("param", value);
? 這種方式就相當(dāng)于重定向之后,在url后面拼接參數(shù),這樣在重定向之后的頁面或者控制器再去獲取url后面的參數(shù)就可以了,但這個(gè)方式因?yàn)槭窃趗rl后面添加參數(shù)的方式,所以暴露了參數(shù),有風(fēng)險(xiǎn)。
attr.addAttribute("param1", "value1");
return "redirect:/index";
? 這樣就相當(dāng)于:return "redirect:/index?param1=value1"
? 第二種:
? attr.addFlashAttribute("param", value);
? 這種方式也能達(dá)到重新向帶參,而且能隱藏參數(shù),其原理就是放到session中,session在跳到頁面后馬上移除對象,所以你刷新一下后這個(gè)值就會(huì)丟掉,這個(gè)方法適合用于防止刷新頁面重復(fù)提交數(shù)據(jù)的問題。
具體使用方法:
controller:
@RequestMapping({"/","/index"})
public String login() {
return "Login";
}
@RequestMapping("info")
public String info(HttpSession session, RedirectAttributes attributes) {
if (session.getAttribute("UserSession") != null)
return "infoShow";
attributes.addFlashAttribute("info",
"<script type='text/javascript'>alert('請登錄賬戶!')</script>");
return "redirect:index";
}
jsp頁面:
<div>${info}</div>
? 這種方法傳遞的參數(shù)是可以被EL表達(dá)式獲取的。
EL表達(dá)式無法獲取傳值的原因:
? 1,請檢查你的“redirect:”的冒號(hào)后面有沒有空格!這個(gè)問題會(huì)導(dǎo)致你的EL表達(dá)式無法獲取你的傳值!切記!不要加空格!不要加空格!不要加空格!重要的事情說三遍!
? 2,網(wǎng)絡(luò)上還有種說法,說是因?yàn)榻邮諈?shù)值的 controller 沒有加上@ModelAttribute的形參,導(dǎo)致無法接收,具體本人也沒有出現(xiàn)過這問題,不是很清楚。