Spring GET 和 POST 映射分开 类

Spring GET and POST mappings in separate classes

我们正在尝试将我们的 Spring 控制器中的 GET 和 POST @RequestMapping 方法分成两个单独的 类。

原因是我们希望 POST 调用有一个异常处理程序,它将响应序列化为 JSON 有效负载,而 GET 调用应该通过 Spring 堆栈向上冒泡.

但是,当我们尝试将它们分开时,我们收到错误提示映射被注册了两次:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0' defined in OSGi resource[classpath:/dispatcher-servlet.xml|bnd.id=21|bnd.sym=com.company.application]: Initialization of bean failed; nested exception is java.lang.IllegalStateException: Cannot map handler 'settingsController' to URL path [/settings.html]: There is already handler of type [class com.company.application.controller.SettingsModelAndViewController$$EnhancerBySpringCGLIB$324809] mapped.

是否可以将 GET 和 POST 请求映射分成两个不同的 类?基本上我们想要(请原谅伪命名约定):

class PostHandler {
    @ExceptionHandler
    public void handleException(...) { // Serialize to JSON }

    @RequestMapping(value = "/settings.html", method = RequestMethod.POST)
    public void saveChanges() { ... }
}

class GetHandler {
    @RequestMapping(value = "/settings.html", method = RequestMethod.GET)
    public ModelAndView getSettings() { ... }
}

但目前无法找到解决 Spring 双重映射投诉的方法。

查看将 URL 路由到 Controller(实际上是 HandlerAdapter 接口)的 DispatcherServlet 的设计和代码,这似乎确实可行,但并不容易,现有的 HandlerMapping 也不行 类 (查看在 https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/HandlerMapping.html). You would have to write a HandlerMapping class (existing handler mappings' code can guide you with this), which would return the right controller based on the URL and HTTP method and configure it (this link should help with HandlerMapping configuration: http://www.baeldung.com/spring-handler-mappings 实现此接口的现有 类)。当前 HandlerMapping None 类 在为 URL 选择控制器时查看 HTTP 方法。

您可以调整 GET 和 POST 请求映射,方法是将通配符添加到其中一个 HTTP 方法处理程序(例如 How do I set priority on Spring MVC mapping?),但不能使用确切的在 2 个不同的控制器中相同 URL。