|
对于最新稳定版本,请使用 Spring Framework 7.0.6! |
@SessionAttributes
@SessionAttributes 用于在请求之间将模型属性存储在 WebSession 中。它是一个类级别的注解,用于声明特定控制器所使用的会话属性。通常,该注解列出模型属性的名称或类型,这些属性应透明地存储在会话中,以便后续请求访问。
考虑以下示例:
-
Java
-
Kotlin
@Controller
@SessionAttributes("pet") (1)
public class EditPetForm {
// ...
}
| 1 | 使用 @SessionAttributes 注解。 |
@Controller
@SessionAttributes("pet") (1)
class EditPetForm {
// ...
}
| 1 | 使用 @SessionAttributes 注解。 |
在第一次请求时,当一个名为 pet 的模型属性被添加到模型中时,
它会自动提升并保存到 WebSession 中。
该属性将一直保留在会话中,直到另一个控制器方法使用 SessionStatus 方法参数来清除存储,
如下例所示:
-
Java
-
Kotlin
@Controller
@SessionAttributes("pet") (1)
public class EditPetForm {
// ...
@PostMapping("/pets/{id}")
public String handle(Pet pet, BindingResult errors, SessionStatus status) { (2)
if (errors.hasErrors()) {
// ...
}
status.setComplete();
// ...
}
}
}
| 1 | 使用 @SessionAttributes 注解。 |
| 2 | 使用 SessionStatus 变量。 |
@Controller
@SessionAttributes("pet") (1)
class EditPetForm {
// ...
@PostMapping("/pets/{id}")
fun handle(pet: Pet, errors: BindingResult, status: SessionStatus): String { (2)
if (errors.hasErrors()) {
// ...
}
status.setComplete()
// ...
}
}
| 1 | 使用 @SessionAttributes 注解。 |
| 2 | 使用 SessionStatus 变量。 |