今天遇到一個需求,在用戶登陸之後,需要將其登陸狀態保存到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 {
//....
}
大功告成