@SessionAttribute
如果你需要访问全局管理的预先存在的会话属性(即控制器外部,例如,由过滤器管理),并且该属性可以存在也可以不存在,那么可以在方法参数上使用 @SessionAttribute
注解,如下例所示:
If you need access to pre-existing session attributes that are managed globally
(that is, outside the controller — for example, by a filter) and may or may not be present,
you can use the @SessionAttribute
annotation on a method parameter, as the following example shows:
-
Java
-
Kotlin
@GetMapping("/")
public String handle(@SessionAttribute User user) { (1)
// ...
}
1 | Using @SessionAttribute . |
@GetMapping("/")
fun handle(@SessionAttribute user: User): String { (1)
// ...
}
1 | Using @SessionAttribute . |
对于需要添加或删除会话属性的用例,请考虑将 WebSession
注入到控制器方法。
For use cases that require adding or removing session attributes, consider injecting
WebSession
into the controller method.
对于在控制器工作流中作为会话的一部分临时存储模型属性,请考虑使用 SessionAttributes
,如 @SessionAttributes
中所述。
For temporary storage of model attributes in the session as part of a controller
workflow, consider using SessionAttributes
, as described in
@SessionAttributes
.