Spring GET和POST映射在不同的类

时间:2018-02-12 21:35:47

标签: java spring spring-mvc http request-mapping

我们试图将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$$54324809] 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双重制图投诉的方法。

1 个答案:

答案 0 :(得分:1)

查看将URL路由到Controller(实际上是HandlerAdapter接口)的DispatcherServlet的设计和代码,它当然可能,但不容易,而不是现有的HandlerMapping类(查看在{实现此接口的现有类) {3}})。您必须编写一个HandlerMapping类(现有的处理程序映射'代码可以指导您),它将根据URL和HTTP方法返回正确的控制器并对其进行配置(此链接应该有助于HandlerMapping配置:{{ 3}})。在为URL选择控制器时,当前的HandlerMapping类都不会查看HTTP方法。

您可以调整GET和POST请求映射,方法是将一个通配符添加到其中一个HTTP方法处理程序(例如https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/HandlerMapping.html),但不要使用完全相同的URL在2个不同的控制器中。