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并没有什么原因造成的验证来触发。
在我看来,Hibernate Bean Validator这可能是annotated随时随地验证bean 字段的最方便的方法之一。它就像setup和forget
我按照此处给出的文档中的说明进行操作
我使用 Gradle 所以,我将添加所需的依赖项,如下所示
// Hibernate Bean validator
compile('org.hibernate:hibernate-validator:5.2.4.Final')
Run Code Online (Sandbox Code Playgroud)
我按照文档中的描述设置了一个 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)
原始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
结果:一切正常。
原始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错误消息的映射。
| 归档时间: |
|
| 查看次数: |
5609 次 |
| 最近记录: |