[Spring MVC] @SessionAttributes remove 如何移除@SessionAttributes Session物件

KouWei.Lee
Nov 12, 2020

做會員登入時一直清不掉Session當中的值

記錄使用Spring @SessionAttributes 的坑

查了api才知道要先將SessionStatus.setComplete()

才會清除@SessionAttributes

問題原因 @SessionAttributes 之後,Spring 無法知道什麼時候要清掉?

setComplete告訴Spring可以清掉了

需要在controller 的 handler method中添加 SessionStatus參數

在方法體中調用SessionStatus#setComplete

什麼是@SessionAttribute?

@SessionAttributes 只能作用在類上,作用是將指定的Model中的鍵值對添加至session中,方便在下一次請求中使用

怎麼使用 @SessionAttribute?

1.Controller上設置參數名稱@SessionAttribute(“參數”)

2.@SessionAttribute參數設到Model中會提升到SessionScope中

SessionAttribute標註的Controller 根據註解的“名稱”對應上則就將該物件放入Session中,直到使用SessionStatus.setComplete() 才會清除

參數匹配上了就也會順便方入Session中

@Controller
@SessionAttributes("personObj")
public class PersonController {

@RequestMapping(value="/person-form")
public ModelAndView personPage() {
return new ModelAndView("person-page", "person-entity", new Person());
}

@RequestMapping(value="/process-person")
public ModelAndView processPerson(Model model,Person person) {
person.setName("Jason"); person.setAge(23);
//因為註解有注解@SessionAttribute 所以person會被存到Session
model.addAttribute("personObj", person);
return modelAndView;
}

}

在這個例子當中 “personObj” 當中的person物件 將會在存放在Session

取出

@RequestMapping("/get")
public String get(@ModelAttribute("personObj") Person
person,ModelMap model,HttpSession httpSession){ System.out.println(model.get("personObj");//可以透過ModelMap取得 System.out.println(person) //透過@ModelAttribute 取得person物件 httpSession.getAttribute("personObj")
}

@SessionAttributes,spring mvc會將模型中對應的屬性暫存到httpSession中

總結

官方建議 一般来说@SessionAttribute 設置參數只用暫時傳遞,如果要長期保存數據還是是要放到Session

也就是@SessionAttributes 作用是將指定的Model中的鍵值對添加至session中,方便在下一次請求中使用

Photo by Emile Perron on Unsplash

參考資料

--

--

No responses yet