Spring 表单控制器泛化

发布于 2024-12-04 04:59:54 字数 678 浏览 0 评论 0原文

在为 spring mvc 应用程序制作控制器时,我必须指定
每次我想从 spring 表单传递一个新的类实例时,都会使用一个新方法:

@RequestMapping(method=RequestMethod.POST)
public String mainPost(@Valid MyClass myClass, 
        BindingResult result, Model model) {
    // do the same stuff each time here
}

所以我需要为应用程序中的每个可能的 MyClass 编写一个方法
可以传递给控制器​​,但所有这些方法都做完全相同的事情
(他们检查错误并将该对象传递给服务层)。

如何将所有这些方法合并为一个?

我相信有一些类似于以下的解决方案(不起作用):

@RequestMapping(method=RequestMethod.POST)
public <T> String mainPost(@Valid T myObject, 
        BindingResult result, Model model) {
    // check errors and pass the object myObject to a service layer
}

When making controller for spring mvc application I have to specify
a new method every time I want to pass a new class instances from spring forms:

@RequestMapping(method=RequestMethod.POST)
public String mainPost(@Valid MyClass myClass, 
        BindingResult result, Model model) {
    // do the same stuff each time here
}

So I need to write a method for every possible MyClass in my application
that can be passed to controller, but all these methods do absolutely the same stuff
(they check for errors and pass this object to service layer).

How can I merge all this methods in one?

I believe that there is some solution similar to the following (that doesn't work):

@RequestMapping(method=RequestMethod.POST)
public <T> String mainPost(@Valid T myObject, 
        BindingResult result, Model model) {
    // check errors and pass the object myObject to a service layer
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

耀眼的星火 2024-12-11 04:59:54

您不能拥有通用控制器方法,但可以创建通用控制器:

public abstract class AbstractController<T> {
    @RequestMapping(method=RequestMethod.POST) 
    public String mainPost(@Valid T myObject,
          BindingResult result, Model model) { ... } 
}

@Controller 
@RequestMapping("/myclass")
public class MyClassController extends AbstractController<MyClass> { ... }

You cannot have generic controller methods, but you can create generic controller:

public abstract class AbstractController<T> {
    @RequestMapping(method=RequestMethod.POST) 
    public String mainPost(@Valid T myObject,
          BindingResult result, Model model) { ... } 
}

@Controller 
@RequestMapping("/myclass")
public class MyClassController extends AbstractController<MyClass> { ... }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文