【发布时间】:2012-03-15 14:15:54
【问题描述】:
有没有办法让 @RequestBody 注释选项(例如 required=false)像 RequestParam 一样支持?
我通过代码的主要路径是使用 POST。但是,出于调试目的,我还想通过浏览器基本 http 请求支持基本 GET 请求。但是,当我尝试这样做时,会收到 415 不支持的媒体错误。
【问题讨论】:
有没有办法让 @RequestBody 注释选项(例如 required=false)像 RequestParam 一样支持?
我通过代码的主要路径是使用 POST。但是,出于调试目的,我还想通过浏览器基本 http 请求支持基本 GET 请求。但是,当我尝试这样做时,会收到 415 不支持的媒体错误。
【问题讨论】:
我通过代码的主要路径是使用 POST。但是,我还想通过浏览器支持基本的 GET 请求
为此,请使用@RequestMapping 注释的method 属性,例如
@RequestMapping(value="/myPath", method=RequestMethod.GET)
public String doSomething() {
...
}
@RequestMapping(value="/myPath", method=RequestMethod.POST)
public String doSomething(@RequestBody payload) {
...
}
【讨论】:
@RequestBody 现在显然可以从 Spring 3.2M1 开始设置为可选:https://jira.springsource.org/browse/SPR-9239
但是,我在 Spring 3.2M2 中对此进行了测试,即使在设置 required=false 之后,它也会在通过 null 正文发送时抛出异常,而不是通过 null。此问题已确认并已修复,计划 3.2 RC1
【讨论】:
有没有办法让 @RequestBody 注释选项(例如 required=false)像 RequestParam 一样支持?
简而言之,我不这么认为, 但您可以从输入流中手动完成:
@Autowired
private MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter;
RestResponse<String> updateViewingCard(@PathVariable(value = "custome") String customer,
@RequestParam(value = "p1", required = false) String p1,
@RequestParam(value = "p2", required = false) String p2,
// @RequestBody MyPayloadType payload, Can't make this optional
HttpServletRequest request,
HttpServletResponse response) throws... {
MyPayloadType payload = null;
if (0 < request.getContentLength()) {
payload = this.mappingJacksonHttpMessageConverter.getObjectMapper().readValue(request.getInputStream(),
MyPayloadType.class);
}
【讨论】:
是的,你可以。在 Spring 4 或 Spring Boot 1.5 中,您可以通过以下方式进行操作:
@PostMapping("/error-report")
public String errorReport(@RequestBody(required = false) ErrorReportModel errorReportModel) {
// YOUR LOGIC
return "page-to-return";
}
【讨论】: