Spring Boot 验证通过 ObjectMapper GET @RequestParam 映射的 JSON

Alw*_*ing 3 java rest spring fasterxml spring-boot

验证在 Spring Boot 中传递到 GET REST 控制器的复杂 JSON 对象的最简单方法是什么,我正在使用com.fasterxml.jackson.databind.ObjectMapper 进行映射?

这是控制器:

@RestController
@RequestMapping("/products")
public class ProductsController {

@GetMapping
public ProductResponse getProducts(
        @RequestParam(value = "params") String requestItem
) throws IOException {
    final ProductRequest productRequest =
            new ObjectMapper()
                    .readValue(requestItem, ProductRequest.class);

    return productRetriever.getProductEarliestAvailabilities(productRequest);
}}
Run Code Online (Sandbox Code Playgroud)

我要验证的 DTO 请求对象:

public class ProductRequest {
private String productId;

public String getProductId() {
    return productId;
}

public void setProductId(String productId) {
    this.productId = productId;
}}
Run Code Online (Sandbox Code Playgroud)

我正在考虑在请求 DTO 上使用注释,但是当我这样做时,它们不会触发任何类型的异常,即@NotNull。我试着使用不同组合@Validated在控制器以及@Valid@RequestParam并没有什么原因造成的验证来触发。

Raf*_*Raf 6

在我看来,Hibernate Bean Validator这可能是annotated随时随地验证bean 字段的最方便的方法之一。它就像setupforget

  • 设置 Hibernate Bean 验证器
  • 配置验证应该如何完成
  • 在任何地方触发 bean 上的验证器

我按照此处给出的文档中的说明进行操作

设置依赖项

我使用 Gradle 所以,我将添加所需的依赖项,如下所示

// Hibernate Bean validator
compile('org.hibernate:hibernate-validator:5.2.4.Final')
Run Code Online (Sandbox Code Playgroud)

创建一个通用的 bean 验证器

我按照文档中的描述设置了一个 bean 验证器接口,然后使用它来验证所有被注释的东西

public interface CustomBeanValidator {
    /**
     * Validate all annotated fields of a DTO object and collect all the validation and then throw them all at once.  
     * 
     * @param object
     */
    public <T> void validateFields(T object); 
}
Run Code Online (Sandbox Code Playgroud)

实现上面的接口如下

@Component
public class CustomBeanValidatorImpl implements CustomBeanValidator {
    ValidatorFactory valdiatorFactory = null; 

    public CustomBeanValidatorImpl() {
        valdiatorFactory = Validation.buildDefaultValidatorFactory(); 
    }

    @Override
    public <T> void validateFields(T object) throws ValidationsFatalException {
        Validator validator = valdiatorFactory.getValidator(); 
        Set<ConstraintViolation<T>> failedValidations = validator.validate(object); 

        if (!failedValidations.isEmpty()) {
            List<String> allErrors = failedValidations.stream().map(failure -> failure.getMessage())
                    .collect(Collectors.toList());
            throw new ValidationsFatalException("Validation failure; Invalid request.", allErrors);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

异常类

ValidationsFatalException上面使用我是延伸自定义异常类RuntimeException。如您所见,我正在传递一条消息和一个列表,violations以防 DTO 有多个验证错误。

public class ValidationsFatalException extends RuntimeException {
    private String message; 
    private Throwable cause;
    private List<String> details; 

    public ValidationsFatalException(String message, Throwable cause) {
        super(message, cause);
    } 

    public ValidationsFatalException(String message, Throwable cause, List<String> details) {
        super(message, cause); 
        this.details = details;
    }

    public List<String> getDetails() {
        return details; 
    }
}
Run Code Online (Sandbox Code Playgroud)

模拟您的场景

为了测试这是否有效,我确实使用您的代码进行了测试,这就是我所做的

  • 创建一个端点,如上所示
  • 自动装配CustomBeanValidator并触发它的validateFields方法传递给productRequest它,如下所示
  • 创建一个ProductRequest如上图所示的类
  • productId@NotNull和注释了@Length(min=5, max=10)
  • 我用Postman做一个GET与请求params具有一个值是url-encodedJSON体

假设CustomBeanValidator在控制器中自动装配,在构造productRequest对象后触发如下验证。

beanValidator.validateFields(productRequest);
Run Code Online (Sandbox Code Playgroud)

如果基于使用的注释有任何违规,上述内容将抛出异常。

异常控制器如何处理异常?

正如标题中提到的,我使用ExceptionController它来处理我的应用程序中的异常。

这是我映射到的exception handler位置的骨架,ValidationsFatalException然后我更新消息并根据异常类型设置所需的状态代码并返回自定义对象(即您在下面看到的 json)

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({SomeOtherException.class, ValidationsFatalException.class})
public @ResponseBody Object handleBadRequestExpection(HttpServletRequest req, Exception ex) {
    if(ex instanceof CustomBadRequestException) 
        return new CustomResponse(400, HttpStatus.BAD_REQUEST, ex.getMessage()); 
    else 
        return new DetailedCustomResponse(400, HttpStatus.BAD_REQUEST, ex.getMessage(),((ValidationsFatalException) ex).getDetails()); 
}
Run Code Online (Sandbox Code Playgroud)

测试 1

原始params = {"productId":"abc123"}
URL 编码的parmas = %7B%22productId%22%3A%22abc123%22%7D
最终 URL:http://localhost:8080/app/product?params=%7B%22productId%22%3A%22abc123%22%7D
结果:一切正常。

测试 2

原始params = {"productId":"ab"}
URL 编码的parmas = %7B%22productId%22%3A%22ab%22%7D
最终 URL:http://localhost:8080/app/product?params=%7B%22productId%22%3A%22ab%22%7D
结果:

{
    "statusCode": 400,
    "status": "BAD_REQUEST",
    "message": "Validation failure; Invalid request.",
    "details": [
        "length must be between 5 and 10"
    ]
}
Run Code Online (Sandbox Code Playgroud)

您可以扩展Validator实现以提供field vs message错误消息的映射。