@RequestBody optional (e.g. required=false)
My main path through the code is with a POST. However, I'd like to also support a basic GET request via a browser
To do this, use the method
attribute of the @RequestMapping
annotation, e.g.
@RequestMapping(value="/myPath", method=RequestMethod.GET)
public String doSomething() {
...
}
@RequestMapping(value="/myPath", method=RequestMethod.POST)
public String doSomething(@RequestBody payload) {
...
}
@RequestBody can apparently now be set as optional as of Spring 3.2M1: https://jira.springsource.org/browse/SPR-9239
However I have tested this in Spring 3.2M2 and its throwing an exception when sending through a null body even after setting required=false, instead of passing through a null. This issue has been confirmed and has been fixed, schedule for 3.2 RC1
Is there a way to make the @RequestBody annotation options (e.g. required=false) like RequestParam supports?
In short, I don't believe so, 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);
}