@SessionAttributes
@SessionAttributes
用於在請求之間將模型屬性儲存在 HTTP Servlet 會話中。它是一個型別級註解,用於宣告特定控制器使用的會話屬性。這通常列出了應透明地儲存在會話中以便後續請求訪問的模型屬性名稱或模型屬性型別。
以下示例使用了 @SessionAttributes
註解
-
Java
-
Kotlin
@Controller
@SessionAttributes("pet") (1)
public class EditPetForm {
// ...
}
1 | 使用 @SessionAttributes 註解。 |
@Controller
@SessionAttributes("pet") (1)
class EditPetForm {
// ...
}
1 | 使用 @SessionAttributes 註解。 |
在第一個請求中,當一個名為 pet
的模型屬性新增到模型中時,它會自動提升並儲存在 HTTP Servlet 會話中。它會一直保留在那裡,直到另一個控制器方法使用 SessionStatus
方法引數清除儲存,如下例所示
-
Java
-
Kotlin
@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 | 在 Servlet 會話中儲存 Pet 值。 |
2 | 從 Servlet 會話中清除 Pet 值。 |
@Controller
@SessionAttributes("pet") (1)
class EditPetForm {
// ...
@PostMapping("/pets/{id}")
fun handle(pet: Pet, errors: BindingResult, status: SessionStatus): String {
if (errors.hasErrors()) {
// ...
}
status.setComplete() (2)
// ...
}
}
1 | 在 Servlet 會話中儲存 Pet 值。 |
2 | 從 Servlet 會話中清除 Pet 值。 |