@SessionAttributes
@SessionAttributes
用于在请求之间将模型属性存储在 HTTP Servlet 会话中。它是一种类型级注解,可声明特定控制器使用的会话属性。这通常会列出应透明地存储在会话中供后续请求访问的模型属性的名称或模型属性的类型。
@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
注解:
The following example uses the @SessionAttributes
annotation:
- Java
-
@Controller @SessionAttributes("pet") (1) public class EditPetForm { // ... }
1 | Using the @SessionAttributes annotation.
|
2 | Using the @SessionAttributes annotation. |
在第一个请求中,当将名为“pet”的模型属性添加到模型时,它会自动提升并保存在 HTTP Servlet 会话中。它会一直保留在那里,直到另一个控制器方法使用 SessionStatus
方法参数清除存储空间,如以下示例所示:
On the first request, when a model attribute with the name, pet
, is added to the model,
it is automatically promoted to and saved in the HTTP Servlet session. It remains there
until another controller method uses a SessionStatus
method argument to clear the
storage, as the following example shows:
- Java
-
@Controller @SessionAttributes("pet") (1) public class EditPetForm { // ... @PostMapping("/pets/{id}") public String handle(Pet pet, BindingResult errors, SessionStatus status) { if (errors.hasErrors) { // ... } status.setComplete(); (2) // ... } }
1 | Storing the Pet value in the Servlet session. |
2 | Clearing the Pet value from the Servlet session.
|
3 | Storing the Pet value in the Servlet session. |
4 | Clearing the Pet value from the Servlet session. |