gpt4 book ai didi

java - 注释 Controller 中的动态命令类

转载 作者:搜寻专家 更新时间:2023-10-31 19:58:37 24 4
gpt4 key购买 nike

从 Spring MVC 3 开始,AbstractCommandController 已弃用,因此您不能再在 setCommandClass() 中指定命令类。相反,您在请求处理程序的参数列表中硬编码命令类。例如,

@RequestMapping(method = RequestMethod.POST)
public void show(HttpServletRequest request, @ModelAttribute("employee") Employee employee)

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

setCommandClass(beanClass)

由于我不能将命令对象声明为方法参数,有没有办法让 Spring 将请求参数绑定(bind)到请求处理程序主体中的通用 bean?

最佳答案

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

@RequestMapping(method = RequestMethod.POST) 
public void show(HttpServletRequest request,
@ModelAttribute("objectToShow") Object objectToShow)
{
...
}

@ModelAttribute("objectToShow")
public Object createCommandObject() {
return getCommandClass().newInstance();
}

顺便说一下,Spring 也可以很好地处理真正的泛型:

public abstract class GenericController<T> {
@RequestMapping("/edit")
public ModelAndView edit(@ModelAttribute("t") T t) { ... }
}

@Controller @RequestMapping("/foo")
public class FooController extends GenericController<Foo> { ... }

关于java - 注释 Controller 中的动态命令类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3897185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com