spring · 2024-09-18 0

DataBinder 使用

1.pom

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.3.22</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>5.3.22</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.22</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-expression</artifactId>
    <version>5.3.22</version>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.28</version>
    <scope>provided</scope>
</dependency>

2.java

@Setter
@Getter
@ToString
public class Pet {

    private Integer id1;

    private String name1;
}
@Test
public void test1() {
    Pet pet = new Pet();
    DataBinder binder = new DataBinder(pet, "pet");
    binder.setValidator(new PetValidator());

    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.add("id1", 123);
    pvs.add("name1", "");

    // 数据绑定
    binder.bind(pvs);
    // 数据校验
    binder.validate();

    try {
        binder.close();
    } catch (BindException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult()
                .getFieldErrors()
                .forEach(error -> errors.put(error.getField(), error.getDefaultMessage()));
        System.out.println(errors);
    }

    BindingResult bindingResult = binder.getBindingResult();

    System.out.println(pet);

    if (bindingResult.hasErrors()) {
        Map<String, String> errors = new HashMap<>();
        bindingResult.getFieldErrors()
                .forEach(error -> errors.put(error.getField(), error.getDefaultMessage()));
        System.out.println(errors);
    }
}

private static class PetValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return Pet.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        Pet user = (Pet) target;

        if (user.getName1() == null || user.getName1().isEmpty()) {
            errors.rejectValue("name1", "400", "name1 can not be empty");
        }
    }
}

结果:

{name1=name1 can not be empty}
Pet(id1=123, name1=)
{name1=name1 can not be empty}