@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
-
@RequestMapping("/") public String handle(@SessionAttribute User user) { 1 // ... }
1 | Using a @SessionAttribute annotation.
|
2 | Using a @SessionAttribute annotation.====== |
对于需要添加或移除会话属性的用例,请考虑将 org.springframework.web.context.request.WebRequest
或 jakarta.servlet.http.HttpSession
注入到控制器方法中。
For use cases that require adding or removing session attributes, consider injecting
org.springframework.web.context.request.WebRequest
or
jakarta.servlet.http.HttpSession
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
.