@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 Pet 值儲存在 Servlet 會話中。
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 Pet 值儲存在 Servlet 會話中。
2 從 Servlet 會話中清除 Pet 值。
© . This site is unofficial and not affiliated with VMware.