|
对于最新的稳定版本,请使用 Spring Framework 7.0.6! |
Model
您可以使用@ModelAttribute注解:
-
在 方法参数 中,在
@RequestMapping个方法 创建或访问模型中的对象并将其绑定到请求通过WebDataBinder。 -
作为方法级别的注解在
@Controller或@ControllerAdvice类中,帮助在任何@RequestMapping方法调用之前初始化模型。 -
在
@RequestMapping方法中标记其返回值为模型属性。
本节讨论 @ModelAttribute 方法,或前面列表中的第二个项。
控制器可以有任意数量的 @ModelAttribute 方法。所有这些方法都在同一控制器中的 @RequestMapping 方法之前被调用。@ModelAttribute 方法也可以通过 @ControllerAdvice 在控制器之间共享。有关详细信息,请参阅控制器建议部分。
@ModelAttribute 方法具有灵活的方法签名。它们支持与 @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);
}
When a name is not explicitly specified, a default name is chosen based on the type,
as explained in the javadoc for Conventions.
You can always assign an explicit name by using the overloaded addAttribute method or
through the name attribute on @ModelAttribute (for a return value). |
Spring WebFlux 显式支持模型中的响应式类型(例如,Mono<Account> 或 io.reactivex.Single<Account>)。这样的异步模型属性可以在 @RequestMapping 调用时透明地解析(并更新模型)为其实际值,前提是声明了一个没有包装器的 @ModelAttribute 参数,如下例所示:
-
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 {
// ...
}
此外,任何具有反应类型包装器的模型属性在视图渲染之前都会解析为其实际值(并更新模型)。
您也可以将 @ModelAttribute 用作方法级别的注解在 @RequestMapping 方法上,在这种情况下,@RequestMapping 方法的返回值被视为模型属性。这通常不是必需的,因为这是 HTML 控制器中的默认行为,除非返回值是 String,否则会被解释为视图名称。@ModelAttribute 还可以帮助自定义模型属性名称,如下例所示:
-
Java
-
Kotlin
@GetMapping("/accounts/{id}")
@ModelAttribute("myAccount")
public Account handle() {
// ...
return account;
}
@GetMapping("/accounts/{id}")
@ModelAttribute("myAccount")
fun handle(): Account {
// ...
return account
}