Spring MVC Model Attributes
Spring MVC Model Attributes are used to bind data either as method parameter or its return value. It is also very commonly used to bind/show data on forms. @ModelAttribute is used to describe a Model Attribute. Lets see the various ways a Model Attribute is used.
@ModelAttribute as a method param
@ModelAttribute as a method param is normally used to access the details on a form.
When we use a @ModelAttribute as a method param, the framework tries to retrieve it from the Model.
If it is not present in the Model, then the param should be instantiated and added to model before using it.
On a form when we pass the instantiated Model Attribute, we need to add the exact matching fields that are present in the Model Attribute object.
This is data binding and is very useful in mapping each form element to the fields in Model Attribute.
We have a EmployeeDetails Object. It has fullName and department fields.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | package com.kscodes.sampleproject.model; public class EmployeeDetails { private String fullName; private String department; public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } } |
To use the EmployeeDetails as a Model Attribute in a form, we need to first instantiate it and add to the Model.
1 2 3 4 | @RequestMapping(value = "/showEmployeeForm") public ModelAndView showEmployeeForm() { return new ModelAndView("employeeForm","employeeModel", new EmployeeDetails()); } |
Now you can the EmployeeDetails object in the form and then use that back as a Model Attribute
1 2 3 4 5 6 | @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) public String addEmployee(@ModelAttribute("employeeModel") EmployeeDetails employeeModel) { // Implement Your Logic } |
@ModelAttribute on a method
Using
@ModelAttribute on a method means you are adding one or more model attributes. You can do it in 2 ways
1. Returning Model Attribute
1 2 3 4 | @ModelAttribute public EmployeeDetails addEmployeeDetails(@RequestParam String empName) { return employeeService.findByName(empName); } |
2. Adding more than one model attribute using Model
1 2 3 4 5 6 | @ModelAttribute public void addEmployeeDetails(@RequestParam String empName, @RequestParam String deptName, Model model) { model.addAttribute("name", empName); model.addAttribute("deptName", deptName); } |
I hope this post helped you in understanding the Spring MVC Model Attributes.