Sunday, May 5, 2024
HomeJavause @ModelAttribute in Spring MVC? Instance Tutorial

use @ModelAttribute in Spring MVC? Instance Tutorial


Hiya guys, there are various annotations in Spring boot which  I’ve shared 5 important Spring Boot annotations earlier and from these, the @ModelAttribute
takes a particular place as this helps to bind a way parameter or technique
return worth
to a named mannequin attribute then exposes it to an online view. So we
are going to debate what’s @ModelAttribute in Spring MVC with an instance
given beneath.  The @ModelAttribute annotation refers to a Mannequin object
attribute (the M in MVC ;). The @ModelAttribute annotation is particular to
Spring-MVC and is used to organize mannequin information. It is also used to specify the
command object that’ll be tied to the info from the HTTP request.

The @ModelAttribute can be utilized on the technique stage or as a way parameter
that may even show the usability and performance of the
annotation. So let’s take a look at @ModelAttribute in Spring MVC.

Previous to engaged on the undertaking, we have to add the next dependencies
in our pom.xml. Right here, represents the pom.xml used within the undertaking.

<?xml model="1.0" encoding="UTF-8"?>
<undertaking 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>
<father or mother>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<model>2.5.0</model>
<relativePath/> <!-- lookup father or mother from repository -->
</father or mother>
<groupId>com.codexlabs</groupId>
<artifactId>spring-cloud-config-server</artifactId>
<model>0.0.1-SNAPSHOT</model>
<identify>spring-modelattribute-example</identify>
<description>Spring boot mannequin attribute annotation</description>
<properties>
<java.model>1.8</java.model>
</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>
<optionally available>true</optionally available>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope >check</scope>
</dependency>
</dependencies>

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

</undertaking>

The spring-boot-starting-thymeleaf is a starter for leveraging Thymeleaf views in MVC net functions.  Spring MVC net functions require the spring-boot-starter-web requirement. Because the default embedded container, it makes use of Tomcat. For automated reloads or stay reloads of apps, spring-boot-devtools is required.

1.1 Technique Degree @ModelAttribute

On the technique stage, the @ModelAttribute is used to map the identical as
@RequestMapping however this cannot be mapped on to requests. 
@ModelAttribute
public void addAttributes(Mannequin mannequin) {
mannequin.addAttribute("message", "Your message in right here!");
}

So in right here, the @ModelAttribute is liable for giving messages to all
the mannequin courses
or controller courses

1.2 Technique Argument @ModelAttribute

On this technique, an argument ought to be retrieved from the mannequin.  If it
is just not current, it ought to be instantiated after which added to the mannequin. As
from the next instance, the Pupil mannequin is populated with information from a
kind submitted to the add pupil endpoint.

@RequestMapping(worth = "/addStudent", technique = RequestMethod.POST)
public String submit(@ModelAttribute("pupil") Pupil pupil) {
// Code that makes use of the coed object

return "studentView";
}
It is also essential to annotate the suitable class with @ControllerAdvice. Because of this, you'll be able to add values to Mannequin that shall be acknowledged as world. Which means a default worth exists for every request and for every technique within the response part.

In order from the above instance, the controller annotated with @RequestMapping
can have customized class arguments annotated with @ModelAtrributes.

2. Type Instance

So in right here, we’re going to talk about methods to submit a kind with pupil
particulars. After submission of the info, how the info is retrieved from the
controller class and displayed will talk about in beneath.

2.1 Type submission with HTML (view)

That is the HTML code phase that’s used to move the info to the Java
controller.

<kind:kind technique="POST" motion="/instance/addstudents" modelAttribute="pupil">
<kind:label path="identify">Identify</kind:label>
<kind:enter path="identify" />

<kind:label path="studentid">Id</kind:label>
<kind:enter path="studentid" />

<enter kind="submit" worth="Submit" />
</kind:kind>


2.2 Controller
Right here is the controller class, the place the logic is applied.
@Controller
@ControllerAdvice
public class StudentController {

personal Map<Lengthy, Pupil> studentMap = new HashMap<>();

@ModelAttribute
public void addAttributes(Mannequin mannequin) {
mannequin.addAttribute("message", "Your message in right here!");
}

@RequestMapping(worth = "/addstudents", technique = RequestMethod.POST)
public String submit(
@ModelAttribute("pupil") Pupil pupil,
BindingResult outcome, ModelMap mannequin) {
if (outcome.hasErrors()) {
return "error";
}
mannequin.addAttribute("identify", pupil.getName());
mannequin.addAttribute("id", pupil.getStudentId());

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

return "studentView";
}

}


So on the finish, studentView known as. That is used to name the respective JSP file within the view consultant.
2.3 Mannequin
The mannequin which is used within the software is given beneath.
@XmlRootElement
public class Pupil {

personal lengthy studentId;
personal String identify;

public Pupil(lengthy studentId, String identify) {
this.studentId = studentId;
this.identify = identify;
}
//getters and setters in right here
}

Naturally, the addAttribute() perform shall be known as first, forward of the opposite @RequestMapping strategies. All @RequestMapping strategies are affected by @ModelAttribute strategies. 

2.4 Present the lead to HTML

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

    <h3>${message}</h3>
    Identify : ${identify}
    StudentId : ${studentId}

So let's have a fast have a look at what are the benefits and usages of @ModelAttributes in Spring MVC.
@ModelAttribute refers to a property of the Mannequin object (the M in MVC ;) so to illustrate now we have a kind with a kind backing object that known as "Particular person" Then you'll be able to have Spring MVC provide this object to a Controller technique through the use of the @ModelAttribute annotation:

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

Alternatively the annotation is used to outline objects which ought to be a part of a Mannequin. So if you wish to have a Particular person object referenced within the Mannequin you need to use the next technique:
@ModelAttribute("particular person")
public Particular person getPerson(){
return new Particular person();
}
This annotated technique will permit entry to the Particular person object in your View, because it will get routinely added to the Fashions by Spring.


@ModelAttribute Instance in Spring MVC

@ModelAttribute refers to a Mannequin object property (the M in MVC ;) So, let's fake now we have a kind with a "Particular person" kind backing object. The @ModelAttribute annotation might then be used to have Spring MVC provide this object to a Controller technique.
public String processForm(@ModelAttribute("particular person") Particular person particular person){
particular person.getStuff();
}

The annotation, alternatively, is used to specify which objects ought to be included

in a Mannequin. If you'd like a Particular person object to be referenced within the Mannequin, use the next

technique:

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

This annotated technique will permit entry to the Particular person object in your View, because it will get routinely added to the Fashions by Spring.

That is all about @ModelAttribute in Spring Framework and Spring MVC specifically. So on this tutorial, we mentioned what's @ModelAttribute in Spring MVC and it is usecases. Hope you perceive what are the usecases of @ModelAttributes for each the tactic stage utilization instances and technique arguments. See you within the subsequent tutorial with one other matter. Till then, bye! 

Different Spring and REST Sources it's possible you'll like
Thanks loads for studying this text to date. In case you like this
Java and Spring MVC tutorial about what's @ModelAttribute and methods to use it then please share them with your folks
and colleagues. When you've got any questions or suggestions then please drop
a be aware. 
P. S. - If you wish to study the Spring Boot framework from
scratch and search for a number of the greatest on-line sources, you can even
try these greatest Spring programs for Java buildersThis text incorporates the most effective Udemy and Pluralsight programs to
study Spring Boot from scratch.             



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments