【问题标题】:Spring boot ConstraintViolationException handler is called only if @PreAuthorize annotation is present仅当存在 @PreAuthorize 注释时才调用 Spring boot ConstraintViolationException 处理程序
【发布时间】:2017-10-09 13:12:33
【问题描述】:

我想实现@PathVariable 验证,因此我为所有带有异常处理程序的控制器创建了一个基类:

  public class BaseController {
    @ExceptionHandler(value = { ConstraintViolationException.class })
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public RestError handleResourceNotFoundException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        StringBuilder strBuilder = new StringBuilder();
        for (ConstraintViolation<?> violation : violations ) {
            strBuilder.append(violation.getMessage());
            strBuilder.append("\n");
        }
        strBuilder.deleteCharAt(strBuilder.lastIndexOf("\n"));

        return new RestError(strBuilder.toString());
    }
}

在扩展 BaseController 的控制器中,以下方法签名按预期工作(返回 {"error": invalid id}):

@PreAuthorize("hasRole('ROLE_VISA_ADMIN')")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
ResponseEntity<UserRepresentation> getUser(@Pattern(regexp = Constants.UUID_REGEX, message = "invalid id")
                                           @PathVariable String id

而没有@PreAuthorize 的相同方法返回状态码500 和消息:org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.ConstraintViolationException. 好像没有异常处理程序一样。

我是 Spring Boot 的新手,所以任何建议都将受到高度赞赏。

编辑

这是控制器的源代码(它实际上实现了描述api的接口):

@RestController
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class UserController extends BaseController implements UserApi {
    private IUserService userService;

    @Override
    public ResponseEntity<UserRepresentation> getUser(@PathVariable String id) {
        UserRepresentation userRepresentation = userService.getUserRepresentationById(id);

        if (userRepresentation == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        } else {
            return new ResponseEntity<>(userRepresentation, HttpStatus.OK);
        }
    }
}

【问题讨论】:

标签: java spring spring-boot


【解决方案1】:

我知道这已经有一段时间了,但我相信您在控制器类中缺少 @Validated 注释。

import org.springframework.validation.annotation.Validated;

@Validated // class level
public class BaseController {
    //...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    • 2011-07-01
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多