@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.

+3


source to share


3 answers


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) {
   ...
}

      

+6


source


@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

+6


source


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);
    }

      

+2


source







All Articles