zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    微软O365使用教程:如何邀请客户试用
    Using the ForeFront Identity Manager to Configure SharePoint 2010’s User Profile Sync Service
    SharePoint2010文档归档策略
    转发:SP 2010: Find error messages with a Correlation ID token in SharePoint 2010
    用sql server的脚本导入Excel2010或Excel2013格式数据
    sharepoint2010的调查的问题总结
    暑假第一周进度报告
    暑假第四周进度报告
    暑假第三周学习进度报告
    暑假第二周进度报告
  • 原文地址:https://www.cnblogs.com/maduar/p/9350061.html
Copyright © 2011-2022 走看看