Spring Boot @ModelAttribute
last modified July 6, 2020
Spring Boot @ModelAttribute tutorial shows how to use the @ModelAttribute
annotation in a Spring
application.
Spring is a popular Java application framework and Spring Boot is an evolution of Spring that helps create stand-alone, production-grade Spring based applications easily.
@ModelAttribute
@ModelAttribute
binds a method parameter or method return value to
a named model attribute, which is exposed to web views. Methods annotated with
@ModelAttribute
are invoked before the controller methods with
@RequestMapping
.
Spring Boot @ModelAttribute example
The following application demonstrates the usage of @ModelAttribute
.
It is used to generate a message of the day in the application. The message is
read from the properties file.
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
This is the project structure.
<?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>
This is the Maven pom.xml
file. The
spring-boot-starter-parent
is a parent POM providing dependency and
plugin management for applications built with Maven. The
spring-boot-starter-thymeleaf
is a starter for building MVC web
applications using Thymeleaf views. The spring-boot-maven-plugin
packages Spring applications into executable JAR or WAR archives.
spring.main.banner-mode=off logging.level.org.springframework=ERROR messages.motd=Welcome
The application.properties
is the main configuration file in Spring Boot.
We turn off the Spring banner and reduce the amount of
logging of the Spring framework by selecting only error messages.
The messages.motd
property contains the message.
package com.zetcode.service; public interface IMessageService { String getMessage(); }
The IMessageService
contains the getMessage()
contract method.
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; } }
The implementation of the getMessage()
method retrieves the
message from the properties file, using the @Value
annotation.
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(); } }
Since MyController
is annotated with a @Controller
annotation,
it becomes a Spring MVC controller class. With @GetMapping
annotation,
we map two URL patterns to Thymeleaf views. Both of these templates receive a motd
model attribute.
@ModelAttribute("motd") public String message() { return messageService.getMessage(); }
A method annotated with @ModelAttribute
is executed before
@RequestMapping
method and their specializations such as @GetMapping
.
The message generated from the messageService
is stored in the motd
model attribute and will be available to both Thymeleaf views.
<!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>
This is pageOne.html
view. The motd
attribute is accessed
with ${}
syntax.
<!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>
This is pageTwo.html
view.
<!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>
This is home page. It contains two links.
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
is the entry point which sets up Spring Boot
application. The @SpringBootApplication
annotation enables
auto-configuration and component scanning. It is a convenience annotation
for @Configuration
, @EnableAutoConfiguration
,
and @ComponentScan
annotations.
$ mvn spring-boot:run
After the application is run, we can navigate to localhost:8080
.
In this tutorial, we have shown how to use @ModelAttribute
annotation in a Spring application.