I have a Spring 3.2 application and I created the REST API after this example based on Spring MVC. Now I am experiencing some problems when trying to check some data for different http methods (for example: POST and PUT).
This will be a fairly simplified example:
public class myItem{ @NotEmpty private String foo; @NotEmpty private String bar; public myItem(String foo){ this.foo = foo; this.bar = ""; } public myItem(String foo, String bar){ this.foo = foo; this.bar = bar; } }
This POJO is reused in different request methods.
This will be my simplified controller:
@Controller @RequestMapping("/api/item") public class myItemController{ @RequestMapping(value="/", method=RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public @ResponseBody myItem createItem(@Valid @RequestBody myItem item){ /* do some stuff */ return item; //inserted item returned } @RequestMapping(value="/", method=RequestMethod.PUT) @ResponseStatus(HttpStatus.NO_CONTENT) public @ResponseBody myItem createItem(@Valid @RequestBody myItem item){ /* do some stuff */ return item //updated item returned } }
In the POST method, I expect the foo field to be set, so this request will complete with annotations up to above. In the PUT method, I expect both the foo and bar fields to be set, so this request will complete successfully.
What is the correct approach to solving such situations: in a specific request method, you do not expect all fields to be filled (some fields may have default values, so you do not want to check all of them, aka create), and in another method you must check all fields (aka update).
source share