@SessionAttributes

@SessionAttributes 用于在请求之间将模型属性存储在 WebSession 中。这是一种类型级注解,用于声明特定控制器使用的会话属性。这通常列出模型属性的名称或模型属性的类型,这些属性应该透明地存储在会话中,以便后续请求访问。

@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
@Controller
@SessionAttributes("pet") 1
public class EditPetForm {
	// ...
}
1 Using the @SessionAttributes annotation.
Kotlin
@Controller
@SessionAttributes("pet") (1)
class EditPetForm {
	// ...
}
2 Using the @SessionAttributes annotation.

在第一个请求中,当名为 pet 的模型属性被添加到模型时,它会自动提升并保存在 WebSession 中。它会一直保留在那里,直到另一个控制器方法使用 SessionStatus 方法参数清除存储,如下例所示:

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
@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.
Kotlin
@Controller
@SessionAttributes("pet") (1)
class EditPetForm {

	// ...

	@PostMapping("/pets/{id}")
	fun handle(pet: Pet, errors: BindingResult, status: SessionStatus): String { (2)
		if (errors.hasErrors()) {
			// ...
		}
		status.setComplete()
		// ...
	}
}
3 Using the @SessionAttributes annotation.
4 Using a SessionStatus variable.