如何确定 ConstraintViolation 是来自 JSON 属性 还是来自 URL 参数?

How to find out whether a ConstraintViolation is from a JSON property or from a URL parameter?

我有一个代码可以从用户那里获取数据并验证它是否有效。

验证是针对来自 URL 的数据和来自 JSON.

的数据

问题是,在 URL 的情况下,路径字段包含 arg0 并且它需要我从 message:

@ValidId (message = "The field is invalid")
private Long field;

字段注释。

JSON 的情况下,我可以简单地从 path.substring(path.lastIndexOf('.') + 1).

中获取字段

protected String buildErrorMessage(ConstraintViolation<?> violation) {
    String path = violation.getPropertyPath().toString();
    String field = path.substring(path.lastIndexOf('.') + 1);
    //field = `arg0` in case of url
    //field = `field` in case of JSON
}

如果我面临 ConstraintViolation - 我怎样才能知道违规是来自 JSON 还是 GET?


编辑

这是我调用 buildErrorMessage 的地方 -

public class ValidationExceptionMapper implements ExceptionMapper<ValidationException> {

    @Override
    public Response toResponse(ValidationException exception) {

        if (exception instanceof ConstraintViolationException) {

            final ConstraintViolationException constraint = (ConstraintViolationException) exception;

            for (final ConstraintViolation<?> violation : constraint.getConstraintViolations()) {
                String message = buildErrorMessage(violation); //HERE
            }
}

GET 是指文本,因为 GET 是您发送的 HTTP 请求类型,JSON/TEXT... 是您发送到服务器的 type/format 数据。

您可以使用下面的代码

 String contentType = request.getContentType();
          if (contentType != null && !contentType.toLowerCase(Locale.US).startsWith(MediaType.APPLICATION_JSON)) {
           //Request is JSON type
          }
    else {
    //Request is TEXT 
    }

它检查请求的 ContentType,如果是 JSON 或 TEXT

在实施 ExceptionMapper to check whether the ConstraintViolation 在 URL 中发送的无效参数或与 在 JSON 有效载荷中发送的无效 属性:

请记住,参数注释如@QueryParam, @PathParam and @MatrixParam可以放在方法参数、资源class字段或资源class bean 属性.


我建议您查看我对 ExceptionMapper for ConstraintViolationException available in GitHub 的实现。

如果你使用spring,你可以在静态方法中获取当前请求,并检查它的类型。

public static HttpServletRequest getCurrentHttpRequest(){
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes instanceof ServletRequestAttributes) {
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        return request;
    }
    logger.debug("Not called in the context of an HTTP request");
    return null;
}

 if(getCurrentHttpRequest().getMethod().toLowerCase()=='get'){
     // text
 }