Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@RequestBody optional (e.g. required=false)

Is there a way to make the @RequestBody annotation options (e.g. required=false) like RequestParam supports?

My main path through the code is with a POST. However, I'd like to also support a basic GET request via a browser basic http request for debugging purposes. However when I try to do that I get a 415 unsupported media error.

like image 267
hockey_dave Avatar asked Mar 15 '12 14:03

hockey_dave


People also ask

What is @RequestBody required false?

@RequestBody Body takes and argument required which is true by default. Specifying it to false will help you. public abstract boolean required. Whether body content is required. Default is true, leading to an exception thrown in case there is no body content.

Can RequestBody be optional?

requestBody consists of the content object, an optional Markdown-formatted description , and an optional required flag ( false by default).

What is @RequestBody used for?

Simply put, the @RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the inbound HttpRequest body onto a Java object. Spring automatically deserializes the JSON into a Java type, assuming an appropriate one is specified.

What is @RequestBody annotation in Spring boot?

The @RequestBody annotation allows us to retrieve the request's body. We can then return it as a String or deserialize it into a Plain Old Java Object (POJO). Spring has built-in mechanisms for deserializing JSON and XML objects into POJOs, which makes this task a lot easier as well.


2 Answers

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) {
   ...
}
like image 101
skaffman Avatar answered Nov 15 '22 05:11

skaffman


@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

like image 32
dleerob Avatar answered Nov 15 '22 05:11

dleerob