Spring @ModelAttribute Annotation with Example





Hey guys in this post we will discuss Spring @ModelAttribute annotation with example.

Overview


@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("person") Person person){
    person.getStuff();
}

Assume that we have a form that is backed by the Person 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("person")
public Person getPerson(){
    return new Person();
}

Here the above method will allow access to the Person 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.

Watch the video


Example on @ModelAttribute


The best way to understand @ModelAttribute annotation is by looking at the example

Create spring boot project


There are many different ways to create a spring boot application, you can follow the below articles to create one –

>> Create spring boot application using Spring initializer
>> Create spring boot application in Spring tool suite [STS]
>> Create spring boot application in IntelliJ IDEA

Add maven dependencies


Open pom.xml and add the following dependencies –

<?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>2.4.3</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>in.bushansirgur</groupId>
	<artifactId>modelattribute</artifactId>
	<version>v1</version>
	<name>modelattribute</name>
	<description>Spring boot model attribute annotation</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</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>

The spring-boot-starter-thymeleaf is a starter for building MVC web applications using Thymeleaf views.




spring-boot-starter-web dependency for building web applications using Spring MVC. It uses the tomcat as the default embedded container. spring-boot-devtools dependency for automatic reloads or live reload of applications.

Create an entity class


Create Customer.java inside the in.bushansirgur.springboot.entity package and add the following content

package in.bushansirgur.springboot.entity;

public class Customer {
	
	private String name;
	
	private Long age;
	
	private String location;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Long getAge() {
		return age;
	}

	public void setAge(Long age) {
		this.age = age;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	@Override
	public String toString() {
		return "Customer [name=" + name + ", age=" + age + ", location=" + location + "]";
	}

	public Customer(String name, Long age, String location) {
		super();
		this.name = name;
		this.age = age;
		this.location = location;
	}
	
}
package in.bushansirgur.springboot.entity;

public class Customer {
	
	private String name;
	
	private Long age;
	
	private String location;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Long getAge() {
		return age;
	}

	public void setAge(Long age) {
		this.age = age;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	@Override
	public String toString() {
		return "Customer [name=" + name + ", age=" + age + ", location=" + location + "]";
	}

	public Customer(String name, Long age, String location) {
		super();
		this.name = name;
		this.age = age;
		this.location = location;
	}
	
}

This is just a plain old java class that has private fields, setters, getters and constructors.

Create a Rest controller


Create CustomerController.java inside the in.bushansirgur.springboot.controller package and add the following content

package in.bushansirgur.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;

import in.bushansirgur.springboot.entity.Customer;

@Controller
public class CustomerController {
	
	@GetMapping("/customer")
	public String getCustomer () {
		return "customer";
	}
	
	@ModelAttribute("customer")
	public Customer customer() {
		return new Customer("Bushan", 28L, "India");
	}
}

We are annotating @ModelAttribute annotation to customer() method which will return the Customer object. @ModelAttribute methods in a controller are invoked before @RequestMapping methods, within the same controller.

Create a view template


Create customer.html inside the templates folder of src/main/resources and add the following content

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<p th:text="'My name is '+${customer.name}+'. I am '+${customer.age}+' years old and I am living in '+${customer.location}"></p>
</body>
</html>

Run the app


Run the application using the below maven command –

mvn spring-boot:run

Open the browser and enter the following URL

  • http://localhost:8080/customer

Screenshot-2021-03-09-at-7-19-21-PM



Our Best Partners: zimpler kasino https://luckyjetwins.com/deposit-withdrawal/ https://luckyjetwins.com/analogues/ dragão demo crazy time statics jogo de fugir do touro talleta ja pelaa tigrinho jogo de aposta online casino that accept google pay pay and play casinos

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply