【发布时间】:2016-01-27 21:01:04
【问题描述】:
使用 Spring Boot (v1.2.6.RELEASE),我需要接受 Controller 方法的 POST 请求。
@RestController
@RequestMapping(value = "/myWebApp/signup")
public class RegController {
@RequestMapping(value = "/registerFamily", method = { RequestMethod.POST }, headers = {"Content-type=application/json"})
@ResponseBody
public FamilylResponse registerFamily(@RequestBody @Valid FamilyRequest familyRequest){
... }
当我从 Chrome/mozilla 的 REST 客户端发送 POST 请求时,响应如下:
{"timestamp":1446008095543,"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request method 'POST' not supported","path":"/myWebApp/signup/registerFamily"}
...
堆栈跟踪如下:
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
at org.springframework.web.servlet.support.WebContentGenerator.checkAndPrepare(WebContentGenerator.java:273)
at org.springframework.web.servlet.support.WebContentGenerator.checkAndPrepare(WebContentGenerator.java:251)
at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.handleRequest(ResourceHttpRequestHandler.java:207)
at org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:51)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
根据Spring: not accept POST request under mvc:resources? how to fix that的回复,
我认为 WebContentGenerator 的其他子类,如 WebContentInterceptor、RequestMappingHandlerAdapter 应该处理对控制器的请求。
另外,在运行 Junit 测试时,我发现 RequestMappingHandlerAdapter 正在处理控制器的这些请求。
但我还没有找到如何配置它来接受 POST 请求?
任何其他更好的解决方案都应该受到欢迎。
编辑:
Tomcat 使用 WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter(WebMvcConfigurerAdapter 的子类) 和
WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter.addResourceHandlers(ResourceHandlerRegistry) 执行以下操作:
o.s.w.s.handler.SimpleUrlHandlerMapping :将 URL 路径 [/webjars/**] 映射到 [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 类型的处理程序上
o.s.w.s.handler.SimpleUrlHandlerMapping :将 URL 路径 [/**] 映射到 [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 类型的处理程序上
在 junit 中,我添加了 WebMvcConfigurerAdapter 的一个空的具体子类。
而 WebMvcConfigurerAdapter.addResourceHandlers(ResourceHandlerRegistry) 什么都不做。
@Configuration
@EnableWebMvc
public class WebAppContext extends WebMvcConfigurerAdapter {}
@Configuration
@Import({ WebAppContext.class })
@PropertySource("classpath:application.properties")
public class ExampleApplicationContext { }
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ExampleApplicationContext.class})
@WebAppConfiguration
public class RegControllerTest { ... }
【问题讨论】:
-
您是否发送
Content-Type标头? -
@zeroflagL,对不起,我发送到错误的 URL。所以,默认的 /** 被采用了