zoukankan      html  css  js  c++  java
  • SpringBoot2 @validated 自定义效验类型

    项目参考:详细参见:《Spring Boot 2精髓:从构建小系统到架构分布式大系统》 第三章 3.5.3节 自定义校验

    项目结构

    WorkTime

    package com.archibladwitwicke.springboot2.chapter03.validated;
    
    import javax.validation.Constraint;
    import javax.validation.Payload;
    import java.lang.annotation.*;
    
    @Constraint(validatedBy = { WorkTimeValidated.class })
    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD})
    public @interface WorkTime {
        String message() default "工作时间不能超过8小时!";
    
        int max() default 8;
    
        Class<?>[] groups() default {};
    
        Class<? extends Payload>[] payload() default {};
    }
    

      

    WorkTimeValidated

    package com.archibladwitwicke.springboot2.chapter03.validated;
    
    import javax.validation.ConstraintValidator;
    import javax.validation.ConstraintValidatorContext;
    
    public class WorkTimeValidated implements ConstraintValidator<WorkTime, Integer> {
    
        private int max;
    
        @Override
        public void initialize(WorkTime work) {
            max = work.max();
        }
    
        @Override
        public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
            Boolean flag = false;
    
            if (value == null || value < max) {
                flag = true;
            }
    
            return flag;
        }
    }
    

      

    UserValidated

    package com.archibladwitwicke.springboot2.chapter03.pojo;
    
    import com.archibladwitwicke.springboot2.chapter03.validated.WorkTime;
    
    import javax.validation.constraints.Max;
    import javax.validation.constraints.NotNull;
    import javax.validation.constraints.Null;
    
    public class UserValidated {
    
        public interface Add {
        }
    
        public interface Update {
        }
    
        @NotNull(groups = Update.class)
        @Null(groups = Add.class)
        private Long id;
    
        @NotNull(message = "名字不能为空!")
        private String name;
    
        @NotNull(message = "年龄不能为空!")
        @Max(value = 100, message = "年龄不能大于100岁!")
        private String age;
    
        @NotNull
        @WorkTime(max = 5, message = "工作时间不能超过5小时!")
        private Integer worktime;
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getAge() {
            return age;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
    
        public Integer getWorktime() {
            return worktime;
        }
    
        public void setWorktime(Integer worktime) {
            this.worktime = worktime;
        }
    }
    

      

    ValidateController

    package com.archibladwitwicke.springboot2.chapter03.controller;
    
    import com.archibladwitwicke.springboot2.chapter03.pojo.UserValidated;
    import org.springframework.stereotype.Controller;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.ObjectError;
    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.List;
    
    @Controller
    @RequestMapping("/validated")
    public class ValidatedController {
    
        @RequestMapping("/validateuser")
        @ResponseBody
        public String validateUser(@Validated UserValidated userValidated, BindingResult bindingResult) {
            String result = null;
    
            if (bindingResult.getErrorCount() == 0) {
                result = "通过验证!";
            }
    
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError error : allErrors) {
                String defaultMessage = error.getDefaultMessage();
                System.out.println(defaultMessage);
            }
    
            return result;
        }
    
    
        @RequestMapping("/validateusergroup")
        @ResponseBody
        public String validateUserByGroup(@Validated UserValidated userValidated, BindingResult bindingResult) {
            String result = null;
    
            if (bindingResult.getErrorCount() == 0) {
                result = "通过验证!";
            }
    
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError error : allErrors) {
                String defaultMessage = error.getDefaultMessage();
                System.out.println(defaultMessage);
            }
    
            return result;
        }
    }
    

      

  • 相关阅读:
    关于“平台”概念的解析
    学习新名词“MVP”(最简可行产品)
    Docker 部署Spring boot 项目如何优雅的关闭(Eureka下线)
    微服务健康监控方案
    Cpu飚高show-busy-java-threads一件脚本排查与Arthas线上诊断工具排查实战
    微服务发展规划(PS 大概分层未细化到具体系统)
    前后端分离研究
    Graphics2D画快递电子面单图片并且打印
    改写rm -rf 脚本
    检查系统信息脚本
  • 原文地址:https://www.cnblogs.com/hfultrastrong/p/8583753.html
Copyright © 2011-2022 走看看