我目前@RequestBody在Spring中遇到了注释问题.我目前正在我的模型上正确设置所有验证注释,并且当对象被POST时它们工作得很好.即使发布的请求主体完全为空或者空对象"{}",一切都按预期工作.当有人试图发布"null"请求主体时会出现问题.这以某种方式通过@Valid注释并没有被捕获,导致NullPointerException我尝试访问该对象.我在下面粘贴了我的控制器片段.
@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);
}
Run Code Online (Sandbox Code Playgroud)
我做了一些检查,itemService.save()看看数据库中是否存在一个项目,因为它被用作upsert.当我访问传递给save的项时,我得到NullPointerException因为item为null.我尝试过使用"required"参数,@RequestBody但只检查是否有POST的内容.如上所述,只有当用户在没有引号作为请求主体的情况下发布"null"时,才会传递空项.是否有自动的Spring注释或配置来阻止此null被传递,或者我应该放入if(item == null) throw new Exception();所有可能出现的控制器?