🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Spring Boot `@ModelAttribute` > 原文: [http://zetcode.com/springboot/modelattribute/](http://zetcode.com/springboot/modelattribute/) Spring Boot `@ModelAttribute`教程显示了如何在 Spring 应用中使用`@ModelAttribute`注解。 Spring 是流行的 Java 应用框架,而 Spring Boot 是 Spring 的演进,可以帮助轻松地创建独立的,生产级的基于 Spring 的应用。 ## `@ModelAttribute` `@ModelAttribute`将方法参数或方法返回值绑定到已公开的 Web 视图的命名模型属性。 用`@ModelAttribute`注解的方法在使用`@RequestMapping`的控制器方法之前被调用。 ## Spring Boot `@ModelAttribute`示例 以下应用演示了`@ModelAttribute`的用法。 它用于在应用中生成当天的消息。 该消息是从属性文件中读取的。 ```java pom.xml src ├── main │ ├── java │ │ └── com │ │ └── zetcode │ │ ├── Application.java │ │ ├── controller │ │ │ └── MyController.java │ │ └── service │ │ ├── IMessageService.java │ │ └── MessageService.java │ └── resources │ ├── application.properties │ ├── static │ │ └── index.html │ └── templates │ ├── pageOne.html │ └── pageTwo.html └── test └── java ``` 这是项目结构。 `pom.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zetcode</groupId> <artifactId>springbootmodelattributeex</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` 这是 Maven `pom.xml`文件。 `spring-boot-starter-parent`是父 POM,它为使用 Maven 构建的应用提供依赖关系和插件管理。 `spring-boot-starter-thymeleaf`是使用 Thymeleaf 视图构建 MVC Web 应用的入门工具。 `spring-boot-maven-plugin`将 Spring 应用打包到可执行的 JAR 或 WAR 归档文件中。 `resources/application.properties` ```java spring.main.banner-mode=off logging.level.org.springframework=ERROR messages.motd=Welcome ``` `application.properties`是 Spring Boot 中的主要配置文件。 我们通过选择错误消息来关闭 Spring 横幅,并减少 Spring 框架的日志记录量。 `messages.motd`属性包含该消息。 `com/zetcode/service/IMessageService.java` ```java package com.zetcode.service; public interface IMessageService { String getMessage(); } ``` `IMessageService`包含`getMessage()`合约方法。 `com/zetcode/service/MessageService.java` ```java package com.zetcode.service; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @Service public class MessageService implements IMessageService { @Value("${messages.motd}") private String motd="Hello"; @Override public String getMessage() { return motd; } } ``` `getMessage()`方法的实现使用`@Value`注解从属性文件中检索消息。 `com/zetcode/controller/MyController.java` ```java package com.zetcode.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.zetcode.service.IMessageService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; @Controller public class MyController { @Autowired private IMessageService messageService; @GetMapping("/pageOne") public String getPageOne() { return "pageOne"; } @GetMapping("/pageTwo") public String getPageTwo() { return "pageTwo"; } @ModelAttribute("motd") public String message() { return messageService.getMessage(); } } ``` 由于`MyController`带有`@Controller`注解,因此它成为 Spring MVC 控制器类。 使用`@GetMapping`注解,我们将两个 URL 模式映射到 Thymeleaf 视图。 这两个模板都接收`motd`模型属性。 ```java @ModelAttribute("motd") public String message() { return messageService.getMessage(); } ``` 在`@RequestMapping`方法及其特化(例如`@GetMapping`)之前,执行带有`@ModelAttribute`注解的方法。 从`messageService`生成的消息存储在`motd`模型属性中,并且可用于两个 Thymeleaf 视图。 `resources/templates/pageOne.html` ```java <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Page one</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h2>Page one</h2> <p th:text="'Message of the day: ' + ${motd}"></p> </body> </html> ``` 这是`pageOne.html`视图。 使用`${}`语法访问`motd`属性。 `resources/templates/pageTwo.html` ```java <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Page two</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h2>Page two</h2> <p th:text="'Message of the day:' + ${motd}"></p> </body> </html> ``` 这是`pageTwo.html`视图。 `resources/static/index.html` ```java <!DOCTYPE html> <html> <head> <title>Home page</title> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <a href="pageOne">Go to page one</a><br> <a href="pageTwo">Go to page two</a> </body> </html> ``` 这是主页。 它包含两个链接。 `com/zetcode/Application.java` ```java package com.zetcode; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` `Application`是设置 Spring Boot 应用的入口。 `@SpringBootApplication`注解启用自动配置和组件扫描。 它是`@Configuration`,`@EnableAutoConfiguration`和`@ComponentScan`注解的便捷注解。 ```java $ mvn spring-boot:run ``` 应用运行后,我们可以导航到`localhost:8080`。 在本教程中,我们展示了如何在 Spring 应用中使用`@ModelAttribute`注解。 您可能也对相关教程感兴趣: [Spring Boot 模型教程](/springboot/model/), [Spring Boot `@PathVariable`教程](/springboot/pathvariable/), [Spring Boot `@RequestParam`教程](/springboot/requestparam/), [Spring Boot `@ResponseBody`教程](/springboot/responsebody/), [Java 教程](/lang/java/)或列出[所有 Spring Boot 教程](/all/#springboot)。