Reputation: 2006
In Spring MVC we have to use org.springframework.ui.Model
instance to pass model to a view. It is not strongly-typed and we have to dynamically build the object like this:
model.addAttribute("departmentID", departmentID);
model.addAttribute("departmentName", departmentName);
model.addAttribute("employees", employees);
However, I came from ASP.NET MVC, where I passed strongly-typed objects to a view, and I had ViewDepartment
class which had departmentID
, departmentName
and employees
fields, and I simply passed instance to a view. Here it doesn't work, but I still need to use ViewDepartment
class, because I occasionally send it as response to AJAX-requests.
So, to get this working in Spring MVC, I need to translate ViewDepartment
object to instance of org.springframework.ui.Model
, one way is to build org.springframework.ui.Model
from HashMap
:
Model.addAllAttributes(Map<String,?> attributes)
The question is, how to build Map<String,?> attributes
from instance of ViewDepartment
class? Creating HashMap object and manually setting each attribute from each property is not option, because it`s not DRY. I need some way to do this with any class, because I have other model classes in other controllers.
Or, may be, someone can tell another solution to this task, related to Spring MVC specifically.
Upvotes: 4
Views: 3602
Reputation: 3504
you could use reflection to get a map of all fields and their values. Be aware, that this gets complicated, if you have nested structures, but with the given example it should work,
public Map<String, Object> toMap( Object object ) throws Exception
{
Map<String, Object> map = new LinkedHashMap<>();
for ( Field field : object.getClass().getDeclaredFields() )
{
field.setAccessible( true );
map.put( field.getName(), field.get( object ) );
}
return map;
}
Upvotes: 3