Spring 检查@PathVariable数据绑定器结果是否为null并抛出404
在我的SpringBoot应用程序中,我有一个用SpringSecurity保护的SpringMVC方法 我将id作为路径变量和spring数据参数解析器传递给该方法,以查找并绑定实体 但当id无效时,实体为空;我想在实体为空时抛出404;因为spring安全预授权需要一个非空实体来检查用户授权; 我的代码是:Spring 检查@PathVariable数据绑定器结果是否为null并抛出404,spring,spring-boot,spring-mvc,spring-data-jpa,spring-data,Spring,Spring Boot,Spring Mvc,Spring Data Jpa,Spring Data,在我的SpringBoot应用程序中,我有一个用SpringSecurity保护的SpringMVC方法 我将id作为路径变量和spring数据参数解析器传递给该方法,以查找并绑定实体 但当id无效时,实体为空;我想在实体为空时抛出404;因为spring安全预授权需要一个非空实体来检查用户授权; 我的代码是: @PutMapping(value = "/{address}") @PreAuthorize("isAuthenticated() and (#address.user.id
@PutMapping(value = "/{address}")
@PreAuthorize("isAuthenticated() and (#address.user.id == #user.id)")
public ResponseEntity<ResponseModel> update(@Valid @RequestBody AddressModel addressModel, @PathVariable Address address, @AuthenticationPrincipal User user) {
try {
addressService.update(user, address, addressModel);
} catch (Exception e) {
return new ResponseEntity<>(new ResponseModel(e.getMessage(), ResponseModel.ResponseStatus.ERROR), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(new ResponseModel(messages.get("def.op.success"), ResponseModel.ResponseStatus.SUCCESS), HttpStatus.OK);
}
但它返回403错误 您不能简单地将注释移动到您的服务中吗
@PutMapping(value = "/{address}")
//@PreAuthorize("isAuthenticated() and
//(#address.user.id == #user.id)") <-- move to service method
public ResponseEntity<ResponseModel> update(
@Valid @RequestBody AddressModel addressModel, @PathVariable Address address,
@AuthenticationPrincipal User user) {
if(address == null){
//throw some exception that gets translated to 404
}
try {
//check will be applied on call to service
addressService.update(user, address, addressModel);
} catch (Exception e) {
return new ResponseEntity<>(new ResponseModel(e.getMessage(),
ResponseModel.ResponseStatus.ERROR), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(new ResponseModel(messages.get("def.op.success"),
ResponseModel.ResponseStatus.SUCCESS), HttpStatus.OK);
}
@PutMapping(value=“/{address}”)
//@预授权(“isAuthenticated()和
//(#address.user.id==#user.id)”)403表示没有访问权限,因此它可能是由isAuthenticated()引发的。请确保您具有访问此文件的正确凭据resource@Mustahsan这是真的;但我提到这部分代码是为了暗示;我的空地址问题
@PutMapping(value = "/{address}")
//@PreAuthorize("isAuthenticated() and
//(#address.user.id == #user.id)") <-- move to service method
public ResponseEntity<ResponseModel> update(
@Valid @RequestBody AddressModel addressModel, @PathVariable Address address,
@AuthenticationPrincipal User user) {
if(address == null){
//throw some exception that gets translated to 404
}
try {
//check will be applied on call to service
addressService.update(user, address, addressModel);
} catch (Exception e) {
return new ResponseEntity<>(new ResponseModel(e.getMessage(),
ResponseModel.ResponseStatus.ERROR), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(new ResponseModel(messages.get("def.op.success"),
ResponseModel.ResponseStatus.SUCCESS), HttpStatus.OK);
}