今天需要針對預覽功能將參數通過window.open(url+參數)的方式請求后台方法,進行頁面跳轉,然而當參數太大時,通過url的方式會導致請求參數過長而失敗。所以只能改用post方式,將參數以bean或者requestbosy的方式傳遞給controller,但是這種方會使原來能自動跳轉的url不跳轉,目前還沒找到原因。通過redirect的方式會導致塞到model的參數無法獲取,因此需要將model參數存入到session中去。參考了以下兩篇原文,供大家參考。
原文參考:http://blog.csdn.net/u012325167/article/details/52426523
https://zhidao.baidu.com/question/476889704.html
今天遇到一個需求,在用戶登陸之后,需要將其登陸狀態保存到Session中。
我的邏輯是:用戶登陸——用戶登陸相關的Controller——驗證完成之后,重定向到首頁相關的Controller,進行相關信息的展示
在這個過程中,我在用戶登陸成功后,利用RedirectAttributes將用戶信息存入到其中,然后重定向到首頁相關的Controller。但是之后遇到了一個問題:在展示數據的時候,第一次展示時,用戶信息是存在的(也就是在剛剛重定向過來的時候),但如果這時候刷新頁面,用戶信息就消失了。這是因為我只把用戶信息存在了RedirectAttributes中,RedirectAttributes之所以能在第一次顯示,其實是利用了Session,它會在第一次跳轉過來之后取到用戶信息,然后再將Session中的用戶信息刪除掉,這就是刷新頁面后信息消失的原因。
為了解決這個問題,我用到了@SessionAttributes。
方法是:
將@SessionAttributes注解到【首頁相關的Controller】上,這樣做的目的是:在用戶驗證完成后,重定向到【首頁相關的Controller】時,將存放在Model中的指定內容存入Session中,這樣以后的地方需要用到該數據時可以直接從Session中獲取。
簡單示例:
用戶登陸的Controller中的驗證方法:
@RequestMapping(value = "/login", method = {RequestMethod.POST}) public String login(String username, String password, RedirectAttributes model) { if ("xxx".equals(username) && "xxx".equals(password)) { model.addFlashAttribute("isAdmin", true); return "redirect:/"; } else { model.addFlashAttribute("errorMsg", "用戶名或密碼錯誤!"); return "redirect:/backend"; } }
在該Controller上注解@SessionAttributes,使得在調用該Controller時,將Model中的數據存入Session
@Controller @RequestMapping("/") @SessionAttributes("isAdmin") public class IndexController extends BasicController { //.... }
大功告成