码迷,mamicode.com
首页 > 编程语言 > 详细

java spring Validator

时间:2018-07-22 15:18:57      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:nbsp   failure   style   ports   font   pos   round   while   get   

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

标签:nbsp   failure   style   ports   font   pos   round   while   get   

原文地址:https://www.cnblogs.com/maduar/p/9350061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!