@SessionAttributes
@SessionAttributes
用於在請求之間將模型屬性儲存在 WebSession
中。它是一種型別層級的註解,用於宣告特定控制器使用的 Session 屬性。這通常列出模型屬性的名稱或模型屬性的類型,這些屬性應透明地儲存在 Session 中,以供後續請求存取。
考慮以下範例
-
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 變數。 |