Java Jersey bean验证-返回错误请求的验证消息

Java Jersey bean验证-返回错误请求的验证消息,java,jersey,jersey-2.0,Java,Jersey,Jersey 2.0,是否可以在错误响应的响应中返回验证注释消息?我认为这是可能的,但我注意到我们的项目没有给出详细的错误请求消息 @NotNull(message="idField is required") @Size(min = 1, max = 15) private String idField; 如果请求缺少idField,我希望返回“idField is required”。我正在使用jersey 2.0。我看到的回应是 { "timestamp": 1490216419752, "stat

是否可以在错误响应的响应中返回验证注释消息?我认为这是可能的,但我注意到我们的项目没有给出详细的错误请求消息

@NotNull(message="idField is required")
@Size(min = 1, max = 15) 
private String idField;
如果请求缺少idField,我希望返回“idField is required”。我正在使用jersey 2.0。我看到的回应是

{
  "timestamp": 1490216419752,
  "status": 400,
  "error": "Bad Request",
  "message": "Bad Request",
  "path": "/api/test"
}

看起来您的Bean验证异常(ConstraintViolationException)是由您的一个ExceptionMapper翻译的。您可以为
ConstraintViolationException
注册
ExceptionMapper
,如下所示,并以所需格式返回数据
ConstraintViolationException
包含您要查找的所有信息

@Singleton
@Provider
public class ConstraintViolationMapper implements ExceptionMapper<ConstraintViolationException> {

  @Override
  public Response toResponse(ConstraintViolationException e) {
    // There can be multiple constraint Violations
    Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
    List<String> messages = new ArrayList<>();
    for (ConstraintViolation<?> violation : violations) {
        messages.add(violation.getMessage()); // this is the message you are actually looking for

    }
    return Response.status(Status.BAD_REQUEST).entity(messages).build();
  }

}
@Singleton
@提供者
公共类ConstraintViolationMapper实现ExceptionMapper{
@凌驾
公众对响应的响应(约束性事件例外){
//可能存在多个约束冲突

Set基于Justin响应,这里是一个使用Java 8流API的版本:

@Singleton
@Provider
public class ConstraintViolationMapper implements ExceptionMapper<ConstraintViolationException> {

    @Override
    public Response toResponse(ConstraintViolationException e) {
        List<String> messages = e.getConstraintViolations().stream()
            .map(ConstraintViolation::getMessage)
            .collect(Collectors.toList());

        return Response.status(Status.BAD_REQUEST).entity(messages).build();
    }

}
@Singleton
@提供者
公共类ConstraintViolationMapper实现ExceptionMapper{
@凌驾
公众对响应的响应(约束性事件例外){
列表消息=e.getConstraintViolations().stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toList());
返回Response.status(status.BAD_REQUEST).entity(messages.build();
}
}

您应该展示如何配置验证器。在自定义约束验证器中,是否有方法为每个违反的约束添加多条消息?@Half\u Duplex您可以通过ex.getConstraintViolations()从异常中获取违反的列表,它们都有自己的消息,您可以根据自己的意愿构建响应消息