Ebooks

Spring Boot @ModelAttribute

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.

$ tree
.
├── 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.

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.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.zetcode</groupId>
    <artifactId>SpringBootModelAttribute</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>       
    
    <dependencies>
        
        <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.

application.properties
server.port=8086
server.contextPath=/myapp

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 set the server port and context path, 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.

IMessageService.java
package com.zetcode.service;

public interface IMessageService {

    public String getMessage();
}

The IMessageService contains the getMessage() contract method.

MessageService.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;
    }
}

The implementation of the getMessage() method retrieves the message from the properties file, using the @Value annotation.

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;

@Controller
public class MyController {
    
    @Autowired
    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.

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}" />

    </body>
</html>

This is pageOne.html view. The motd attribute is accessed with ${} syntax.

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>
            <p th:text="'Message of the day:' + ${motd}" />
        </p>

    </body>
</html>

This is pageTwo.html view.

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.html">Go to page one</a><br>
        <a href="pageTwo.html">Go to page two</a>
    </body>
</html>

This is home page. It contains two links.

Application.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 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:8086/myapp/.

In this tutorial, we have shown how to use @ModelAttribute annotation in a Spring application. You might also be interested in the related tutorials: Spring Boot Model tutorial, Spring Boot @PostConstruct tutorial, Spring Boot @Controller tutorial, Spring Boot @ExceptionHandler tutorial, Spring Boot @Component, Spring Boot @PathVariable tutorial, Spring Boot @RequestParam tutorial, Spring Boot @ResponseBody tutorial, Java tutorial.