@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 變數。 |