有時候咱們可能會遇到需要將數據傳入重定向的頁面當中的情形,比如登錄成功後重定向到項目主頁,並顯示提示信息。這時就需要將登錄驗證中得到的驗證結果傳入重定向之後的頁面。
使用RedirectAttributes 可以達到我們想要的效果,他是專門用於重定向攜帶參數跳轉的的工具類,它有兩種實現方式:
第一種:
使用redirectAttributes.addAttributie(“param”,value);
這種方法相當於在重定向鏈接地址追加傳遞的參數。
注意:這種方法會將傳遞的參數直接暴露在鏈接地址上,很不安全。
url會變成:xxx/main?param=value
public String xxx(RedirectAttributes redirectAttributes) {
redirectAttributes.addAttributie("param",value);
return:"redirect:main"
}
第二種:
使用redirectAttributes.addFlashAttributie(“param”,value);
這種方法隱藏了參數,但是能且只能在重定向的 “頁面” (如jsp頁面)中獲取param參數值。
原理:該屬性值被放到session中,session在跳到頁面後馬上移除對象。若是重定向到controller中,則獲取不到該屬性值。除非在controller中用(@RequestParam(value = “param”)String param)註解
在controller中取得param的方法:
public String xxx(RedirectAttributes redirectAttributes) {
redirectAttributes.addAttributie("param",value);
return:"redirect:yyy"
}
@RequestMapping("/yyy")
public Map<Object,Object> forYYY(@RequestParam(value = "pparam")String param, ...){
System.out.println(param);
//your code
}
參考博文:
[1].關於重定向RedirectAttributes的用法