我想比较我的实体中的两个字段,并检查maxField是否大于minField有效。下面是我的实现,但我看不到自定义消息,而是返回400 bad request:
{
"errors": []
}
字符串
我的dto:
@ValidMaxMinDouble(
maxFieldName = "maxOperatingTemperature",
minFieldName = "minOperatingTemperature",
message =
"Maximum operating temperature must not be less than the minimum operating temperature")
@Data
public class RequestDTO {
@ValidDoubleRange(min = -100, max = 100, required = true)
private Double maxOperatingTemperature;
@ValidDoubleRange(min = -100, max = 100, required = true)
private Double minOperatingTemperature;
}
型
这是我的validator:
@Documented
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ValidMaxMinDoubleValidator.class)
public @interface ValidMaxMinDouble {
String message() default "The maximum value must be greater than or equal to the minimum value";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String maxFieldName();
String minFieldName();
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface List {
ValidMaxMinDouble[] value();
}
}
class ValidMaxMinDoubleValidator implements ConstraintValidator<ValidMaxMinDouble, Object> {
private String maxFieldName;
private String minFieldName;
private String message;
@Override
public void initialize(ValidMaxMinDouble constraintAnnotation) {
this.maxFieldName = constraintAnnotation.maxFieldName();
this.minFieldName = constraintAnnotation.minFieldName();
this.message = constraintAnnotation.message();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
Double maxValue = (Double) new BeanWrapperImpl(value).getPropertyValue(maxFieldName);
Double minValue = (Double) new BeanWrapperImpl(value).getPropertyValue(minFieldName);
if (maxValue == null || minValue == null) {
return false;
}
boolean valid = maxValue >= minValue;
if (!valid && !message.isEmpty()) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
}
return valid;
}
}
型
我不知道为什么我看不到自定义错误消息。我发送的请求触发context.disabledisableDefaultConstraintViolation()部分。
1条答案
按热度按时间ep6jt1vc1#
我在这里复制https://github.com/sbernardo/spring-issues-examples/tree/main/sof-questions-77724410的情况下。
文档pom.xml:
字符串
我还添加了一个
@ControllerAdvice
来拦截所有错误,并返回一个带有自定义消息的BadRequest
。您可以自定义响应结构。让我知道如果错过了什么,希望这将有助于;)