0% found this document useful (0 votes)
56 views2 pages

Using @ModelAttribute in Spring MVC

The document explains the use of the @ModelAttribute annotation in a Spring application to simplify data binding in request handling methods. It demonstrates how to assign custom names to model attributes and provides examples of using @ModelAttribute to bind an Alien object and a course value. Additionally, it shows how to declare a method to provide the course name for use in the view.

Uploaded by

shravanparthe
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views2 pages

Using @ModelAttribute in Spring MVC

The document explains the use of the @ModelAttribute annotation in a Spring application to simplify data binding in request handling methods. It demonstrates how to assign custom names to model attributes and provides examples of using @ModelAttribute to bind an Alien object and a course value. Additionally, it shows how to declare a method to provide the course name for use in the view.

Uploaded by

shravanparthe
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Using ModelAttribute

Advanced Usage:
● Custom names can be assigned to objects using
@ModelAttribute("customName").

Now, using @ModelAttribute, we can simplify things in a single annotation.

@RequestMapping("addAlien")
public String addAlien(@ModelAttribute Alien alien) {
return "result";
}

Output:

Suppose you want to use a different name as alien1.

@RequestMapping("addAlien")
public String addAlien(@ModelAttribute("alien") Alien alien) {
return "result";
}

By default, @ModelAttribute is provided.

@RequestMapping("addAlien")
public String addAlien(Alien alien) {
return "result";
}
Suppose you want to use course value inside view,

<body>
<h2>Welcome To Telusko</h2>
<p>${alien}</p>
<p>Welcome to the ${course} World</p>
</body>

⇨ You need to separately declare the course.


⇨ Create the method courseName inside HomeController.

@ModelAttribute("course")
public String courseName() {
return "Java";
}

You might also like