It can be done using request level model attributes as follows:
Suppose There is ObjectInterace is an interface with three implementation classes as ObjectA, ObjectB and ObjectC. then Controller method declaration is:
@RequestMapping(path="/doSomething", method=RequestMethod.POST)
public String doSomething(@ModelAttribute("object") ObjectInterface formInfo) {
...
}
Add Method to populate modelattribute in the controller class:
@ModelAttribute("object")
public ObjectInterface getModelObject(HttpServletRequest request) {
ObjectInterface object = null;
String type = request.getParameter("type");
if (StringUtils.equals("A", type)) {
object= new objectA();
} else if (StringUtils.equals("B", type)){
object= new objectB();
}else if (StringUtils.equals("C", type)){
object= new objectC();
}else{
//object=any default object.
}
return object ;
}
the value returned by getModelObject is added to the Model and it will be populated with the values from the view to the controller method.
Before invoking the handler method, Spring invokes all the methods that have @ModelAttribute annotation. It adds the data returned by these methods to a temporary Map object. The data from this Map would be added to the final Model after the execution of the handler method.