java spring Validator

Posted 金色元年

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java spring Validator相关的知识,希望对你有一定的参考价值。

1. Validation using Spring’s Validator interface

Spring features a Validator interface that you can use to validate objects. The Validator interface works using an Errors object so that while validating, validators can report validation failures to the Errors object.

 

2. data object:

public class KmailPostForm {
    private Integer kid;

    public KmailPostForm() {
    }

    public Integer getKid() {

        return kid;
    }

    public void setKid(Integer kid) {
        this.kid = kid;
    }
}

3. validator:

import com.maduar.springbootdemo.form.KmailPostForm;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class KmailPostFormValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return KmailPostForm.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors, "kid", "kid.empty");
        KmailPostForm kmailPostForm = (KmailPostForm) target;
        if (kmailPostForm.getKid() == null) {
            errors.rejectValue("kid", "kid is null");
        } else if (kmailPostForm.getKid().intValue() < 0) {
            errors.rejectValue("kid", "kid < 0");
        }
    }
}

  

  4. controller

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @InitBinder
    public void initBinder(DataBinder dataBinder) {
        dataBinder.setValidator(new KmailPostFormValidator());
    }


    @PostMapping(value = "/helloPost/")
    public HttpEntity<?> helloPost(@Valid @RequestBody KmailPostForm kmailPostForm, BindingResult result) {

        if (result.hasErrors()) {
            return ResponseEntity.ok("error");
        }

        return ResponseEntity.ok("OK");
    }

}

  

a: springboot 版本 1.5.9.RELEASE

b: https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#validation

以上是关于java spring Validator的主要内容,如果未能解决你的问题,请参考以下文章

Java Hibernate Validator JSR-303验证

Java Hibernate Validator JSR-303验证

用好spring mvc validator可以简化代码

使用validator-api来验证spring-boot的参数

使用validator-api来验证spring-boot的参数

Spring - HV000030: No validator could be found for constraint ‘xx‘ validating type ‘java.lang.Intege