Spring Boot @ModelAttribute 教程显示了如何在 Spring 应用中使用@ModelAttribute
注解。
Spring 是流行的 Java 应用框架,而 Spring Boot 是 Spring 的演进,可以帮助轻松地创建独立的,生产级的基于 Spring 的应用。
@ModelAttribute
@ModelAttribute
将方法参数或方法返回值绑定到已公开的 Web 视图的命名模型属性。 用@ModelAttribute
注解的方法在使用@RequestMapping
的控制器方法之前被调用。
Spring Boot @ModelAttribute
示例
以下应用演示了@ModelAttribute
的用法。 它用于在应用中生成当天的消息。 该消息是从属性文件中读取的。
这是项目结构。
pom.xml
这是 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
application.properties
是 Spring Boot 中的主要配置文件。 我们通过选择错误消息来关闭 Spring 横幅,并减少 Spring 框架的日志记录量。
messages.motd
属性包含该消息。
com/zetcode/service/IMessageService.java
IMessageService
包含getMessage()
合约方法。
com/zetcode/service/MessageService.java
getMessage()
方法的实现使用@Value
注解从属性文件中检索消息。
com/zetcode/controller/MyController.java
由于MyController
带有@Controller
注解,因此它成为 Spring MVC 控制器类。 使用@GetMapping
注解,我们将两个 URL 模式映射到 Thymeleaf 视图。 这两个模板都接收motd
模型属性。
在@RequestMapping
方法及其特长(例如@GetMapping
)之前,执行带有@ModelAttribute
注解的方法。 从messageService
生成的消息存储在motd
模型属性中,并且可用于两个 Thymeleaf 视图。
resources/templates/pageOne.html
这是pageOne.html
视图。 使用${}
语法访问motd
属性。
resources/templates/pageTwo.html
这是pageTwo.html
视图。
resources/static/index.html
这是主页。 它包含两个链接。
com/zetcode/Application.java
Application
是设置 Spring Boot 应用的入口。 @SpringBootApplication
注解启用自动配置和组件扫描。 它是@Configuration
,@EnableAutoConfiguration
和@ComponentScan
注解的便捷注解。
应用运行后,我们可以导航到localhost:8080
。
在本教程中,我们展示了如何在 Spring 应用中使用@ModelAttribute
注解。