Spring Validator验证器与Web Formatter

2022/7/25 23:24:17

本文主要是介绍Spring Validator验证器与Web Formatter,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Spring Validator验证器与Web Formatter

Validator

Spring提供了Validator接口和注解帮助对业务数据进行验证,这些方法可以不仅在Web端使用

使用 Spring 的 Validator 接口进行验证

Validator 接口通过使用 Error 对象来工作,在进行验证时,可以向 Error 对象报告验证失败

该接口有两个方法,分别为:

  • supports(Class):这个验证器是否可以验证该类的对象
  • validate(Object, org.springframework.validation.Errors):验证给定的对象

可以使用ValidationUtils 工具类帮助进行验证:

public class PersonValidator implements Validator {

    /**
     * This Validator validates only Person instances
     */
    public boolean supports(Class clazz) {
        return Person.class.equals(clazz);
    }

    public void validate(Object obj, Errors e) {
        ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
        Person p = (Person) obj;
        if (p.getAge() < 0) {
            e.rejectValue("age", "negativevalue");
        } else if (p.getAge() > 110) {
            e.rejectValue("age", "too.darn.old");
        }
    }
}

Validator 也可以嵌套,实现逻辑的重用

自定义约束

自定义验证约束由两部分组成:

  • 一个是@Constraint,作为元注解
  • 实现ConstraintValidator 接口,定义具体的验证行为

自定义一个注解:

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=MyConstraintValidator.class)
public @interface MyConstraint {
}

实现ConstraintValidator接口:

import javax.validation.ConstraintValidator;

public class MyConstraintValidator implements ConstraintValidator {

    @Autowired;
    private Foo aDependency;

    // ...
}

Spring实现了:LocalValidatorFactoryBean,该类实现了java的验证器以及Spring的验证器

Formatter

core.Convert下定义了类型转换的逻辑,而在web端也有对接口数据编解转换的需求,Spring提供了Formatter接口便于解决这些问题。

接口定义:

package org.springframework.format;

public interface Formatter<T> extends Printer<T>, Parser<T> {
}

该接口扩展了Printer和Parser,具体来说是print和parse这对方法

我们可以自定义Formatter注解,实现 AnnotationFormatterFactory即可:

package org.springframework.format;

public interface AnnotationFormatterFactory<A extends Annotation> {

    Set<Class<?>> getFieldTypes();

    Printer<?> getPrinter(A annotation, Class<?> fieldType);

    Parser<?> getParser(A annotation, Class<?> fieldType);
}

方法解析:

  • getFieldTypes返回支持的类类型
  • getPrinter返回输出Printer对象
  • getParser返回解析Parser对象

一个示例:

public final class NumberFormatAnnotationFormatterFactory
        implements AnnotationFormatterFactory<NumberFormat> {

    public Set<Class<?>> getFieldTypes() {
        return new HashSet<Class<?>>(asList(new Class<?>[] {
            Short.class, Integer.class, Long.class, Float.class,
            Double.class, BigDecimal.class, BigInteger.class }));
    }

    public Printer<Number> getPrinter(NumberFormat annotation, Class<?> fieldType) {
        return configureFormatterFrom(annotation, fieldType);
    }

    public Parser<Number> getParser(NumberFormat annotation, Class<?> fieldType) {
        return configureFormatterFrom(annotation, fieldType);
    }

    private Formatter<Number> configureFormatterFrom(NumberFormat annotation, Class<?> fieldType) {
        if (!annotation.pattern().isEmpty()) {
            return new NumberStyleFormatter(annotation.pattern());
        } else {
            Style style = annotation.style();
            if (style == Style.PERCENT) {
                return new PercentStyleFormatter();
            } else if (style == Style.CURRENCY) {
                return new CurrencyStyleFormatter();
            } else {
                return new NumberStyleFormatter();
            }
        }
    }
}


这篇关于Spring Validator验证器与Web Formatter的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程