Spring Boot @ModelAttribute 教程显示了如何在 Spring 应用中使用@ModelAttribute注解。
Spring 是流行的 Java 应用框架,而 Spring Boot 是 Spring 的演进,可以帮助轻松地创建独立的,生产级的基于 Spring 的应用。
@ModelAttribute
@ModelAttribute将方法参数或方法返回值绑定到已公开的 Web 视图的命名模型属性。 用@ModelAttribute注解的方法在使用@RequestMapping的控制器方法之前被调用。
Spring Boot @ModelAttribute示例
以下应用演示了@ModelAttribute的用法。 它用于在应用中生成当天的消息。 该消息是从属性文件中读取的。
pom.xmlsrc├── 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
<?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.0http://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
spring.main.banner-mode=offlogging.level.org.springframework=ERRORmessages.motd=Welcome
application.properties是 Spring Boot 中的主要配置文件。 我们通过选择错误消息来关闭 Spring 横幅,并减少 Spring 框架的日志记录量。
messages.motd属性包含该消息。
com/zetcode/service/IMessageService.java
package com.zetcode.service;public interface IMessageService { String getMessage();}IMessageService包含getMessage()合约方法。
com/zetcode/service/MessageService.java
package com.zetcode.service;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;@Servicepublic class MessageService implements IMessageService { @Value("${messages.motd}") private String motd="Hello"; @Override public String getMessage() { return motd; }}getMessage()方法的实现使用@Value注解从属性文件中检索消息。
com/zetcode/controller/MyController.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;@Controllerpublic 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模型属性。
@ModelAttribute("motd")public String message() { return messageService.getMessage();}在@RequestMapping方法及其特长(例如@GetMapping)之前,执行带有@ModelAttribute注解的方法。 从messageService生成的消息存储在motd模型属性中,并且可用于两个 Thymeleaf 视图。
resources/templates/pageOne.html
<!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
<!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
<!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
package com.zetcode;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}Application是设置 Spring Boot 应用的入口。 @SpringBootApplication注解启用自动配置和组件扫描。 它是@Configuration,@EnableAutoConfiguration和@ComponentScan注解的便捷注解。
$ mvn spring-boot:run
应用运行后,我们可以导航到localhost:8080。
在本教程中,我们展示了如何在 Spring 应用中使用@ModelAttribute注解。
