Spring @ModelAttribute Annotation Example

In this section we will learn about @ModelAttribute Annotation. 


The @ModelAttribute annotation refers to the Model object in MVC. We can pass @ModelAttribute annotation to method arguments or we can even annotate a method as well. 

Passing @ModelAttribute to method argument indicates that the value should bind to the method argument.
public String processForm(@ModelAttribute("user") User user){
    user.doStuff();
}

Assume that we have a form that is backed by the User object, when the user submits the form, the values should bind to the method argument with the help of @ModelAttribute annotation. 

By annotating @ModelAttribute annotation to method defines the object, which will automatically be added to the Model, and later we can use the Model object inside the view template.

@ModelAttribute("user")
public User getUser(){
    return new User();
}


Here the above method will allow access to the User object in our View since it gets automatically gets added to the Models by Spring. 

Methods annotated with @ModelAttribute are invoked PRIOR TO every @RequestMapping method that is invoked in the same controller class. This is generally used for populating read-only components for a form – eg the values for a select list.

The following example creates a Spring Boot web application which uses @ModelAttribute

Project Directory


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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.knf.dev.demo</groupId>
<artifactId>spring-modelattribute-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-modelattribute-example</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>


User.java

package com.knf.dev.demo.model;

public class User {

private String firstName;

private String lastName;

private String emailId;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmailId() {
return emailId;
}

public void setEmailId(String emailId) {
this.emailId = emailId;
}

public User(String firstName, String lastName, String emailId) {
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
}
}


UserController.java

package com.knf.dev.demo.controller;

import com.knf.dev.demo.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;

@Controller
public class UserController {

@GetMapping("/user")
public String getuser () {
return "user";
}

@ModelAttribute("user")
public User user() {
return new User("Sibin", "Alpha", "sibin@gmail.com");
}
}


user.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>User</title>
</head>
<body>
First Name: <span th:text="${user.firstName}"></span><br>
Last Name: <span th:text="${user.lastName}"></span><br>
Email: <span th:text="${user.emailId}"></span>
</body>
</html>


Run Application - Application.java

Application is the entry point that sets up the Spring Boot application. The @SpringBootApplication annotation enables auto-configuration and component scanning.
Let's run this Spring boot application from either IntelliJ IDEA IDE by right click - Run 'Application.main()'
Or you can use the below maven command to run:

mvn spring-boot:run


Open the browser and enter the following URL

  • http://localhost:8080/user

Download Source Code

More related topics,

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete