对于最新的稳定版本,请使用 Spring Framework 6.2.4spring-doc.cadn.net.cn

Model

您可以使用@ModelAttribute注解:spring-doc.cadn.net.cn

本节讨论@ModelAttribute方法或前面列表中的第二项。 控制器可以具有任意数量的@ModelAttribute方法。所有这些方法都是 之前调用@RequestMapping方法。一个@ModelAttribute方法也可以通过@ControllerAdvice.有关更多详细信息,请参阅 Controller Advice 部分。spring-doc.cadn.net.cn

@ModelAttribute方法具有灵活的方法签名。它们支持许多相同的 arguments 设置为@RequestMapping方法(除了@ModelAttribute自身和任何事物 与请求正文相关)。spring-doc.cadn.net.cn

以下示例使用@ModelAttribute方法:spring-doc.cadn.net.cn

@ModelAttribute
public void populateModel(@RequestParam String number, Model model) {
	model.addAttribute(accountRepository.findAccount(number));
	// add more ...
}
@ModelAttribute
fun populateModel(@RequestParam number: String, model: Model) {
	model.addAttribute(accountRepository.findAccount(number))
	// add more ...
}

以下示例仅添加一个属性:spring-doc.cadn.net.cn

@ModelAttribute
public Account addAccount(@RequestParam String number) {
	return accountRepository.findAccount(number);
}
@ModelAttribute
fun addAccount(@RequestParam number: String): Account {
	return accountRepository.findAccount(number);
}
如果未明确指定名称,则根据类型选择默认名称。 如 Javadoc 中所述Conventions. 您始终可以使用重载的addAttributemethod 或 通过 name 属性@ModelAttribute(对于返回值)。

与 Spring MVC 不同,Spring WebFlux 在模型中显式支持响应式类型 (例如,Mono<Account>io.reactivex.Single<Account>).这种异步模型 属性可以透明地解析(并更新模型)为其实际值 在@RequestMappingininvokecation 中,提供了@ModelAttributeargument 是 在没有包装器的情况下声明,如下例所示:spring-doc.cadn.net.cn

@ModelAttribute
public void addAccount(@RequestParam String number) {
    Mono<Account> accountMono = accountRepository.findAccount(number);
    model.addAttribute("account", accountMono);
}

@PostMapping("/accounts")
public String handle(@ModelAttribute Account account, BindingResult errors) {
	// ...
}
import org.springframework.ui.set

@ModelAttribute
fun addAccount(@RequestParam number: String) {
	val accountMono: Mono<Account> = accountRepository.findAccount(number)
	model["account"] = accountMono
}

@PostMapping("/accounts")
fun handle(@ModelAttribute account: Account, errors: BindingResult): String {
	// ...
}

In addition, any model attributes that have a reactive type wrapper are resolved to their actual values (and the model updated) just prior to view rendering.spring-doc.cadn.net.cn

You can also use @ModelAttribute as a method-level annotation on @RequestMapping methods, in which case the return value of the @RequestMapping method is interpreted as a model attribute. This is typically not required, as it is the default behavior in HTML controllers, unless the return value is a String that would otherwise be interpreted as a view name. @ModelAttribute can also help to customize the model attribute name, as the following example shows:spring-doc.cadn.net.cn

@GetMapping("/accounts/{id}")
@ModelAttribute("myAccount")
public Account handle() {
	// ...
	return account;
}
@GetMapping("/accounts/{id}")
@ModelAttribute("myAccount")
fun handle(): Account {
	// ...
	return account
}