Thursday, April 20, 2023

How to use @ModelAttribute in Spring MVC? Example Tutorial

Hello guys, there are many annotations in Spring boot which  I have shared 5 essential Spring Boot annotations earlier and from those, the @ModelAttribute takes a special place as this helps to bind a method parameter or method return value to a named model attribute then exposes it to a web view. So we are going to discuss what is @ModelAttribute in Spring MVC with an example given below.  The @ModelAttribute annotation refers to a Model object attribute (the M in MVC ;). The @ModelAttribute annotation is special to Spring-MVC and is used to prepare model data. It's also used to specify the command object that'll be tied to the data from the HTTP request.

The @ModelAttribute can be used at the method level or as a method parameter that will also demonstrate the usability and functionality of the annotation. So let's have a look at @ModelAttribute in Spring MVC.

Prior to working on the project, we need to add the following dependencies in our pom.xml. Here, represents the pom.xml used in the project.

<?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.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.codexlabs</groupId>
<artifactId>spring-cloud-config-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-modelattribute-example</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-starting-thymeleaf is a starter for leveraging Thymeleaf views in MVC web applications.  Spring MVC web applications require the spring-boot-starter-web requirement. As the default embedded container, it utilizes Tomcat. For automated reloads or live reloads of apps, spring-boot-devtools is required.




1.1 Method Level @ModelAttribute

At the method level, the @ModelAttribute is used to map the same as @RequestMapping but this can not be mapped directly to requests. 

@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("message", "Your message in here!");
}

So in here, the @ModelAttribute is responsible for giving messages to all the model classes or controller classes


1.2 Method Argument @ModelAttribute

In this method, an argument should be retrieved from the model.  If it is not present, it should be instantiated and then added to the model. As from the following example, the Student model is populated with data from a form submitted to the add student endpoint.

@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String submit(@ModelAttribute("student") Student student) {
// Code that uses the student object

return "studentView";
}
It's also crucial to annotate the appropriate class with @ControllerAdvice. As a result, you can add values to Model that will be recognized as global. This means that a default value exists for each request and for each method in the response section.
So as from the above example, the controller annotated with @RequestMapping can have custom class arguments annotated with @ModelAtrributes.




2. Form Example

So in here, we are going to discuss how to submit a form with student details. After submission of the data, how the data is retrieved from the controller class and displayed will discuss in below.

2.1 Form submission with HTML (view)

This is the HTML code segment that is used to pass the data to the Java controller.
<form:form method="POST" action="/example/addstudents" modelAttribute="student">
<form:label path="name">Name</form:label>
<form:input path="name" />

<form:label path="studentid">Id</form:label>
<form:input path="studentid" />

<input type="submit" value="Submit" />
</form:form>

2.2 Controller
Here is the controller class, where the logic is implemented.
@Controller
@ControllerAdvice
public class StudentController {

private Map<Long, Student> studentMap = new HashMap<>();


@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("message", "Your message in here!");
}

@RequestMapping(value = "/addstudents", method = RequestMethod.POST)
public String submit(
@ModelAttribute("student") Student student,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("name", student.getName());
model.addAttribute("id", student.getStudentId());

studentMap.put(student.getStudentId(), student);

return "studentView";
}

}

So at the end, studentView is called. This is used to call the respective JSP file in the view representative.
2.3 Model
The model which is used in the application is given below.
@XmlRootElement
public class Student {

private long studentId;
private String name;

public Student(long studentId, String name) {
this.studentId = studentId;
this.name = name;
}
//getters and setters in here
}
Naturally, the addAttribute() function will be called first, ahead of the other @RequestMapping methods. All @RequestMapping methods are affected by @ModelAttribute methods. 

2.4 Show the result in HTML

So let's print the result which is taken from the  controller class.

    <h3>${message}</h3>
    Name : ${name}
    StudentId : ${studentId}

So let's have a quick look at what are the advantages and usages of @ModelAttributes in Spring MVC.
@ModelAttribute refers to a property of the Model object (the M in MVC ;) so let's say we have a form with a form backing object that is called "Person" Then you can have Spring MVC supply this object to a Controller method by using the @ModelAttribute annotation:

public String processForm(@ModelAttribute("person") Person person){
person.getStuff();
}

On the other hand the annotation is used to define objects which should be part of a Model. So if you want to have a Person object referenced in the Model you can use the following method:
@ModelAttribute("person")
public Person getPerson(){
return new Person();
}
This annotated method will allow access to the Person object in your View, since it gets automatically added to the Models by Spring.


@ModelAttribute Example in Spring MVC

@ModelAttribute refers to a Model object property (the M in MVC ;) So, let's pretend we have a form with a "Person" form backing object. The @ModelAttribute annotation may then be used to have Spring MVC supply this object to a Controller method.
public String processForm(@ModelAttribute("person") Person person){
person.getStuff();
}

The annotation, on the other hand, is used to specify which objects should be included

in a Model. If you want a Person object to be referenced in the Model, use the following

method:

@ModelAttribute("person")
public Person getPerson(){
return new Person();
}

This annotated method will allow access to the Person object in your View, since it gets automatically added to the Models by Spring.
That's all about @ModelAttribute in Spring Framework and Spring MVC in particular. So in this tutorial, we discussed what is @ModelAttribute in Spring MVC and it's usecases. Hope you understand what are the usecases of @ModelAttributes for both the method level usage cases and method arguments. See you in the next tutorial with another topic. Until then, bye! 

Other Spring and REST Resources you may like
Thanks a lot for reading this article so far. If you like this Java and Spring MVC tutorial about what is @ModelAttribute and how to use it then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note. 

P. S. - If you want to learn the Spring Boot framework from scratch and look for some of the best online resources, you can also check out these best Spring courses for Java developersThis article contains the best Udemy and Pluralsight courses to learn Spring Boot from scratch.             

No comments :

Post a Comment