Spring MVC 提供兩種使用 Session 的方式:直接注入 HttpSession、或使用 @SessionAttributes 註解。本文重點剖析註解方式的底層原理與常見誤區。
Model(如 model.addAttribute("userId", 123)),若類上標註 @SessionAttributes("userId"),框架會在視圖渲染後自動將該屬性複製到 Session 中。userId 並預填充到 Model 中,方法參數可直接通過 @ModelAttribute("userId") 或 Map 獲取。HttpSession 取值。註解本身不提供清除 API,必須注入 HttpSession 手動移除:
@RequestMapping("/logout")
public String logout(HttpSession session) {
session.removeAttribute("userId"); // 對應 @SessionAttributes 的值
return "redirect:/login";
}
也可調用SessionStatus.setComplete()標記會話結束,框架會清除所有@SessionAttributes聲明的屬性。
| 維度 | Model | HttpServletRequest |
|---|---|---|
| 定位 | 視圖渲染數據容器 | 客戶端請求信息載體 |
| 生命週期 | 當前請求(含轉發) | 當前請求 |
| 清理時機 | 視圖渲染完成後自動清空 | 請求結束自動銷毀 |
| 視圖取值 | OGNL/EL 表達式直接取值 | 需 request.getAttribute() |
設計初衷:HttpServletRequest 職責單一——承載請求參數、Header 等客戶端信息,不應承擔「模型數據傳遞給視圖」的職責。Model 專為模型-視圖解耦設計,渲染後自動清理,避免污染請求域。
Model/ModelAndView 傳遞視圖數據,保持 Controller 純淨。@SessionAttributes 適用於「多步驟表單、向導式流程」等跨請求共享少量數據場景。HttpSession,便於精確控制生命週期。@SessionAttributes 失效。