Use @RequestBody with optional body in latest Spring v4

Solution 1:

@Santosh, I'm not sure which required argument you're referring. Mike already mentioned that he tried using @RequestBody (required=false) and request was still null. May be you can elaborate more & give example.

@Mike, probably you can try to have another separate converter that will serve your purpose.

Note: I noticed same issue with Spring v4.1.6 & Mike could be using that as he mentioned he is using latest version.

Solution 2:

You can use java.util.Optional:

@RequestMapping(value="/add/employee", method=RequestMethod.POST)
public void addEmployee(@RequestBody Optional<Employee> employee){
    // ...
}

Solution 3:

I guess you are using spring version above 3.2 as there was a issue with the version. @RequestBody should have a required parameter to allow a request body to be optional

Have a look at following link Spring @RequestBody Anotation

@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. Switch this to false if you prefer null to be passed when the body content is null.