Spring attribute scope

  • 390
  • 0
  • 2018-02-06

Spring MVC 中呼叫下列方法後,便可以在 Request Scope 中取得該變數

model.addAttribute("account", "dennis")

那麼是如何辦到的呢??

首先,Spring 會先將變數儲存到 Model 中,接著在呼叫 Controller 之前,會先在 Model 儲存變數的 Map 中尋找,若沒有特別設定的話會將尋找到的變數儲存到 Request scope 中

所以若要將變數存入 session scope 則可以透過 @SessionAttributes

@Controller
@SessionAttributes("loginedAccount")
public class UserController {
    @RequestMapping(method= {RequestMethod.POST}, path= {"/login.controller"})
    public String login(Model model, String account, String password) {
        Map<String, String> errors = new HashMap<>();
        model.addAttribute("errors", errors);
        
        if (!loginService.verifyUser(account, password)) {
            errors.put("errorMessage", "帳號不存在或密碼錯誤");
            return "loginPage";
        }
        
        model.addAttribute("loginedAccount", account);
        return "index";
    }

在呼叫 Controller 之前也是會到 Model map 中尋找符合名稱的變數,接著將之存入 session scope 中

但是在使用 @SessionAttributes 時會出現一個問題,若想透過將 session scope 設為 null 來移除變數會因為這個原因失敗,必須使用以下方法才能將變數從 session scope 中刪除

@RequestMapping(method= {RequestMethod.GET}, path= {"/logout.controller"})
public String logout(SessionStatus status) {
    status.setComplete();
    return "index";
}

前面主要是如何將變數加入到 session scope 中,那要如何透過 Spring 將已經在 session scope 中的變數取出呢?

可以透過 @ModelAttribute 搭配 @SessionAttributes 來做到

@Controller
@SessionAttributes("loginedAccount")
public class UserController {
    @RequestMapping(method= {RequestMethod.GET}, path= {"/logout.controller"})
    public String logout(@ModelAttribute("loginedAccount")String loginedAccount) {
        ....

透過以上方法 Spring 就會將 session scope 中名稱符合的變數綁定後傳入

 

參考網址:

http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/spring-model-attribute-handler-param/

https://www.intertech.com/Blog/understanding-spring-mvc-model-and-session-attributes/