1. 程式人生 > >Spring Boot 2.0 教程 | @ModelAttribute 註解

Spring Boot 2.0 教程 | @ModelAttribute 註解

ali mode contain ria string public 手動 ble block

歡迎關註微信公眾號: 小哈學Java
文章首發於個人網站: https://www.exception.site/springboot/spring-boot-model-attribute

Spring Boot 2.0 中的註解 @ModelAttribute 有什麽作用呢?

通常情況下,我們會將 @ModelAttribute 註解放置在 Controller 中的某個方法上,那麽,如果您在請求這個 Controller 中定義的 URI 時,會首先調用這個被註解的方法,並將該方法的結果作為 Model 的屬性,然後才會調用對應 URI 的處理方法。

一、@ModelAttribute 使用場景

我們通常會通過 @ModelAttribute 來向某個 Controller 中需要的公共模型 Model 中添加數據。如下面的示例代碼所示。

二、示例代碼

@ModelAttribute
public void findUserById(@PathVariable("userId") Long userId, Model model) {
    model.addAttribute("user", userService.findUserById(userId));
}

@GetMapping("/user/{userId}")
public String findUser(Model model) {
    System.out.println(model.containsAttribute("user"));
    return "success !";
}

當我們請求接口 /user/1 時,會先調用 findUserById 方法,方法內,通過 userId 查詢到對應的 User 對象放置到 Model 模型中。

需要註意,如果您僅僅只是添加一個對象到 Model 模型中,上面的代碼還可以再精煉一點:

@ModelAttribute
public User findUserById(@PathVariable("userId") Long userId) {
    return userService.findUserById(userId);
}

通過上述的代碼,返回的 User 對象會被自動添加到 Model 模型中,就相當於您手動調用了 model.addAttribute(user)

方法。

歡迎關註公眾號: 小哈學Java

技術分享圖片

Spring Boot 2.0 教程 | @ModelAttribute 註解