This version is still in development and is not considered stable yet. For the latest stable version, please use Spring Framework 6.1.12! |
@SessionAttributes
@SessionAttributes
is used to store model attributes in the WebSession
between
requests. It is a type-level annotation that declares 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.
Consider the following example:
-
Java
-
Kotlin
@Controller
@SessionAttributes("pet") (1)
public class EditPetForm {
// ...
}
1 | Using the @SessionAttributes annotation. |
@Controller
@SessionAttributes("pet") (1)
class EditPetForm {
// ...
}
1 | Using the @SessionAttributes annotation. |
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 WebSession
. It remains there until
another controller method uses a SessionStatus
method argument to clear the storage,
as the following example shows:
-
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 | Using the @SessionAttributes annotation. |
2 | Using a SessionStatus variable. |
@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 | Using the @SessionAttributes annotation. |
2 | Using a SessionStatus variable. |