@RequestBody optional (e.g. required = false)
Is there a way to make @RequestBody annotation parameters (e.g. required = false) like RequestParam?
My main path through the code is with POST. However, I would like to also support a basic GET request with a basic browser HTTP request for debugging purposes. However, when I try to do this, I get 415 unsupported media errors.
source to share
My main path through the code is with POST. However, I would like to also support a basic GET request through the browser
To do this, use an method
annotation attribute @RequestMapping
, eg.
@RequestMapping(value="/myPath", method=RequestMethod.GET)
public String doSomething() {
...
}
@RequestMapping(value="/myPath", method=RequestMethod.POST)
public String doSomething(@RequestBody payload) {
...
}
source to share
@RequestBody apparently can now be set as optional as Spring 3.2M1: https://jira.springsource.org/browse/SPR-9239
However, I tested this in Spring 3.2M2 and excluded it when dispatched through a null body even after setting required = false instead of skipping null. This issue has been confirmed and fixed, graph for 3.2 RC1
source to share
Is there a way to make @RequestBody annotation parameters (e.g. required = false) like RequestParam?
Long story short, I don't believe it, but you can do it manually from the input stream:
@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);
}
source to share