对于最新的稳定版本,请使用 Spring Framework 6.2.4! |
Model
您可以使用@ModelAttribute
注解:
本节讨论@ModelAttribute
方法或前面列表中的第二项。
控制器可以具有任意数量的@ModelAttribute
方法。所有这些方法都是
之前调用@RequestMapping
方法。一个@ModelAttribute
方法也可以通过@ControllerAdvice
.有关更多详细信息,请参阅 Controller Advice 部分。
@ModelAttribute
方法具有灵活的方法签名。它们支持许多相同的
arguments 设置为@RequestMapping
方法(除了@ModelAttribute
自身和任何事物
与请求正文相关)。
以下示例使用@ModelAttribute
方法:
-
Java
-
Kotlin
@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 ...
}
以下示例仅添加一个属性:
-
Java
-
Kotlin
@ModelAttribute
public Account addAccount(@RequestParam String number) {
return accountRepository.findAccount(number);
}
@ModelAttribute
fun addAccount(@RequestParam number: String): Account {
return accountRepository.findAccount(number);
}
如果未明确指定名称,则根据类型选择默认名称。
如 Javadoc 中所述Conventions .
您始终可以使用重载的addAttribute method 或
通过 name 属性@ModelAttribute (对于返回值)。 |
与 Spring MVC 不同,Spring WebFlux 在模型中显式支持响应式类型
(例如,Mono<Account>
或io.reactivex.Single<Account>
).这种异步模型
属性可以透明地解析(并更新模型)为其实际值
在@RequestMapping
ininvokecation 中,提供了@ModelAttribute
argument 是
在没有包装器的情况下声明,如下例所示:
-
Java
-
Kotlin
@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.
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:
-
Java
-
Kotlin
@GetMapping("/accounts/{id}")
@ModelAttribute("myAccount")
public Account handle() {
// ...
return account;
}
@GetMapping("/accounts/{id}")
@ModelAttribute("myAccount")
fun handle(): Account {
// ...
return account
}