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";
}