原文: 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的用法。 它用于在应用中生成当天的消息。 该消息是从属性文件中读取的。

  1. pom.xml
  2. src
  3. ├── main
  4. ├── java
  5. └── com
  6. └── zetcode
  7. ├── Application.java
  8. ├── controller
  9. └── MyController.java
  10. └── service
  11. ├── IMessageService.java
  12. └── MessageService.java
  13. └── resources
  14. ├── application.properties
  15. ├── static
  16. └── index.html
  17. └── templates
  18. ├── pageOne.html
  19. └── pageTwo.html
  20. └── test
  21. └── java

这是项目结构。

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <groupId>com.zetcode</groupId>
  8. <artifactId>springbootmodelattributeex</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>jar</packaging>
  11. <properties>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. <maven.compiler.source>11</maven.compiler.source>
  14. <maven.compiler.target>11</maven.compiler.target>
  15. </properties>
  16. <parent>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-parent</artifactId>
  19. <version>2.1.1.RELEASE</version>
  20. </parent>
  21. <dependencies>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-web</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  29. </dependency>
  30. </dependencies>
  31. <build>
  32. <plugins>
  33. <plugin>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-maven-plugin</artifactId>
  36. </plugin>
  37. </plugins>
  38. </build>
  39. </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

  1. spring.main.banner-mode=off
  2. logging.level.org.springframework=ERROR
  3. messages.motd=Welcome

application.properties是 Spring Boot 中的主要配置文件。 我们通过选择错误消息来关闭 Spring 横幅,并减少 Spring 框架的日志记录量。

messages.motd属性包含该消息。

com/zetcode/service/IMessageService.java

  1. package com.zetcode.service;
  2. public interface IMessageService {
  3. String getMessage();
  4. }

IMessageService包含getMessage()合约方法。

com/zetcode/service/MessageService.java

  1. package com.zetcode.service;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.stereotype.Service;
  4. @Service
  5. public class MessageService implements IMessageService {
  6. @Value("${messages.motd}")
  7. private String motd="Hello";
  8. @Override
  9. public String getMessage() {
  10. return motd;
  11. }
  12. }

getMessage()方法的实现使用@Value注解从属性文件中检索消息。

com/zetcode/controller/MyController.java

  1. package com.zetcode.controller;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Controller;
  4. import com.zetcode.service.IMessageService;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.ModelAttribute;
  7. @Controller
  8. public class MyController {
  9. @Autowired
  10. private IMessageService messageService;
  11. @GetMapping("/pageOne")
  12. public String getPageOne() {
  13. return "pageOne";
  14. }
  15. @GetMapping("/pageTwo")
  16. public String getPageTwo() {
  17. return "pageTwo";
  18. }
  19. @ModelAttribute("motd")
  20. public String message() {
  21. return messageService.getMessage();
  22. }
  23. }

由于MyController带有@Controller注解,因此它成为 Spring MVC 控制器类。 使用@GetMapping注解,我们将两个 URL 模式映射到 Thymeleaf 视图。 这两个模板都接收motd模型属性。

  1. @ModelAttribute("motd")
  2. public String message() {
  3. return messageService.getMessage();
  4. }

@RequestMapping方法及其特化(例如@GetMapping)之前,执行带有@ModelAttribute注解的方法。 从messageService生成的消息存储在motd模型属性中,并且可用于两个 Thymeleaf 视图。

resources/templates/pageOne.html

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <title>Page one</title>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. </head>
  8. <body>
  9. <h2>Page one</h2>
  10. <p th:text="'Message of the day: ' + ${motd}"></p>
  11. </body>
  12. </html>

这是pageOne.html视图。 使用${}语法访问motd属性。

resources/templates/pageTwo.html

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <title>Page two</title>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. </head>
  8. <body>
  9. <h2>Page two</h2>
  10. <p th:text="'Message of the day:' + ${motd}"></p>
  11. </body>
  12. </html>

这是pageTwo.html视图。

resources/static/index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Home page</title>
  5. <meta charset="UTF-8"/>
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. </head>
  8. <body>
  9. <a href="pageOne">Go to page one</a><br>
  10. <a href="pageTwo">Go to page two</a>
  11. </body>
  12. </html>

这是主页。 它包含两个链接。

com/zetcode/Application.java

  1. package com.zetcode;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class Application {
  6. public static void main(String[] args) {
  7. SpringApplication.run(Application.class, args);
  8. }
  9. }

Application是设置 Spring Boot 应用的入口。 @SpringBootApplication注解启用自动配置和组件扫描。 它是@Configuration@EnableAutoConfiguration@ComponentScan注解的便捷注解。

  1. $ mvn spring-boot:run

应用运行后,我们可以导航到localhost:8080

在本教程中,我们展示了如何在 Spring 应用中使用@ModelAttribute注解。 您可能也对相关教程感兴趣: Spring Boot 模型教程Spring Boot @PathVariable教程Spring Boot @RequestParam教程Spring Boot @ResponseBody教程Java 教程或列出所有 Spring Boot 教程