[英]Spring Framework's Validation is Not Working with JSR-303 Validation
[英]JSR-303 validation in Spring controller and getting @JsonProperty name
我在我的 Spring 应用程序中使用JSR-303
进行验证,它可以根据需要工作。
这是一个例子:
@Column(nullable = false, name = "name")
@JsonProperty("customer_name")
@NotEmpty
@Size(min = 3, max = 32)
private String name;
并且 REST API 客户端使用customer_name
作为输入字段的名称,该名称发送到 API 芽验证字段错误org.springframework.validation.FieldError
返回name
作为字段的名称。
有什么方法可以获取在@JsonProperty
中指定的JSON-ish
风格的名称吗? 还是我必须实现自己的映射器将类字段名称映射到其 JSON 替代项?
Edit1:将类字段重命名为与 JSON 名称相对应的名称是不可替代的(出于多种原因)。
这现在可以通过使用PropertyNodeNameProvider来完成。
目前没有办法实现这一点。 我们在参考实现中有一个问题: HV-823 。
这将解决 Hibernate Validator 方面的问题(即从Path.Node#getName()
返回您期望的名称),它需要更多检查 Spring 是否真的从那里获取名称。
也许您有兴趣帮助实现这个?
对于MethodArgumentNotValidException
和BindException
,我编写了一个尝试通过反射从 Spring ViolationFieldError
访问私有ConstraintViolation
的方法。
/**
* Try to get the @JsonProperty annotation value from the field. If not present then the
* fieldError.getField() is returned.
* @param fieldError {@link FieldError}
* @return fieldName
*/
private String getJsonFieldName(final FieldError fieldError) {
try {
final Field violation = fieldError.getClass().getDeclaredField("violation");
violation.setAccessible(true);
var constraintViolation = (ConstraintViolation) violation.get(fieldError);
final Field declaredField = constraintViolation.getRootBeanClass()
.getDeclaredField(fieldError.getField());
final JsonProperty annotation = declaredField.getAnnotation(JsonProperty.class);
//Check if JsonProperty annotation is present and if value is set
if (annotation != null && annotation.value() != null && !annotation.value().isEmpty()) {
return annotation.value();
} else {
return fieldError.getField();
}
} catch (Exception e) {
return fieldError.getField();
}
}
此代码可用于在具有@ControllerAdvice
的类中处理 BindExceptions @ExceptionHandler(BindException.class)
的方法中:
@ControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(BindException.class)
public ResponseEntity<YourErrorResultModel> handleBindException(final BindException exception) {
for (FieldError fieldError : exception.getBindingResult().getFieldErrors()) {
final String fieldName = getJsonFieldName(fieldError);
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.