As of Spring MVC 3, AbstractCommandController
is deprecated so you can no longer specify the command class in setCommandClass()
. Instead you hard-code the command class in the parameter list of a request handler. For example,
@RequestMapping(method = RequestMethod.POST)
public void show(HttpServletRequest request, @ModelAttribute("employee") Employee employee)
My problem is that I'm developing a generic page that allows the user to edit a generic bean, so the command class isn't known until the run-time. If the variable beanClass
holds the command class, with AbstractCommandController
, you would simply do the following,
setCommandClass(beanClass)
Since I can't declare the command object as a method parameter, is there any way to have Spring bind request parameters to a generic bean in the body of the request handler?
Instantiation of the command object is the only place where Spring needs to know a command class. However, you can override it with @ModelAttribute
-annotated method:
@RequestMapping(method = RequestMethod.POST)
public void show(HttpServletRequest request,
@ModelAttribute("objectToShow") Object objectToShow)
{
...
}
@ModelAttribute("objectToShow")
public Object createCommandObject() {
return getCommandClass().newInstance();
}
By the way, Spring also works fine with the real generics:
public abstract class GenericController<T> {
@RequestMapping("/edit")
public ModelAndView edit(@ModelAttribute("t") T t) { ... }
}
@Controller @RequestMapping("/foo")
public class FooController extends GenericController<Foo> { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With