Spring MVC @SessionAttributes和@SessionAttribute用法
@SessionAttributes
@SessionAttributes is used to store model attributes in the HTTP Servlet session between requests. It is a type-level annotation that declares the session attributes used by a specific controller. This typically lists the names of model attributes or types of model attributes that should be transparently stored in the session for subsequent requests to access.
通俗的讲,@SessionAttributes透明的将在某个方法中保存的session提升到了类级别,这样对于此Controller中的所有方法都可见。那这又有什么用呢?当然时方便操作了。传统方式上,我们通过HttpSession的setAttribute方法保存了两个session(a和b),当要删除a和b时,一般我们会再次通过HttpSession的removeAttribute进行删除。现在我们可以利用@SessionAttributes将session a 和 b声明为类级别,这样,就可以通过此Controller中的任一方法传入SessionStatus参数,调用其setComplete方法一次将a 和 b清除,这样操作明显简洁了。
代码
@RestController
@SessionAttributes("a", "b")