Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Command Class in Annotated Controller

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?

like image 905
Tom Tucker Avatar asked Oct 09 '10 17:10

Tom Tucker


Video Answer


1 Answers

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> { ... }
like image 198
axtavt Avatar answered Sep 21 '22 01:09

axtavt