带注释的控制器中的动态命令类

带注释的控制器中的动态命令类

问题描述:

从Spring MVC 3开始,不推荐使用AbstractCommandController,因此您不能再在setCommandClass()中指定命令类.相反,您可以在请求处理程序的参数列表中对命令类进行硬编码.例如

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)

我的问题是我正在开发一个允许用户编辑通用bean的通用页面,因此直到运行时才知道命令类.如果变量beanClass使用AbstractCommandController保存命令类,则只需执行以下操作,

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)

由于我无法将命令对象声明为方法参数,因此有什么方法可以让Spring将请求参数绑定到请求处理程序主体中的泛型bean?

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?

Spring唯一需要知道命令类的地方就是命令对象的实例化.但是,您可以使用@ModelAttribute注释的方法覆盖它:

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();
}

顺便说一句,Spring也可以与真正的泛型一起很好地工作:

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> { ... }