I am currently facing a problem with @RequestBody annotation in Spring. Currently, I have all of my validation annotations installed on my models, and they work fine when the object is POSTED. Everything works as expected, even when the request body is sent as a completely empty or empty object "{}". The problem occurs when someone tries to send the request body "null". This somehow goes through the @Valid annotation and doesn't get caught, @Valid NullPointerException when trying to access the object. I pasted a snapshot of my controller below.
@Secured({ ROLE_ADMIN }) @RequestMapping(method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE } ) public HttpEntity<Resource<Item>> addItem(@RequestBody @Valid Item item) throws Exception { Resource<Item> itemResource = this.itemResourceAssembler.toResource(this.itemService.save(item)); return new ResponseEntity<Resource<Item>>(itemResource, HttpStatus.CREATED); }
I do some checks in itemService.save() to find out if an item already exists in the database since it is used as upsert. When I access the element passed for storage, I get a NullPointerException because the element is null. I tried using the "required" @RequestBody parameter, but it only checks if there is something POSTed. As indicated above, a null element is only transmitted when the user sends a βzeroβ without quotes as the body of the request. Is there an automatic annotation or Spring configuration to stop this null value, or should I just put if(item == null) throw new Exception(); to all my controllers, where can this happen?
java null spring-mvc annotations request
Zasrin
source share