zoukankan      html  css  js  c++  java
  • 第5章—构建Spring Web应用程序—关于spring中的validate注解后台校验的解析

    关于spring中的validate注解后台校验的解析

    在后台开发过程中,对参数的校验成为开发环境不可缺少的一个环节。比如参数不能为null,email那么必须符合email的格式,如果手动进行if判断或者写正则表达式判断无意开发效率太慢,在时间、成本、质量的博弈中必然会落后。所以把校验层抽象出来是必然的结果,下面说下几种解决方案。

    1.简单的校验Demo

    依赖:

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    

    Student:

    import javax.validation.constraints.*;
    import java.math.BigDecimal;
    import java.util.Date;
    
    public class Student {
    
            @NotNull(message = "名字不能为空")
            private String name;
    
            @Size(min = 6, max = 30, message = "地址应该在6-30字符之间")
            private String address;
    
            @DecimalMax(value = "100.00", message = "体重有些超标哦")
            @DecimalMin(value = "60.00", message = "多吃点饭吧")
            private BigDecimal weight;
    
            private String friendName;
    
            @AssertTrue
            private Boolean isHaveFriend() {
                return friendName != null ? true : false;
            }
    
            @Future(message = "生日必须在当前实践之前")
            private Date birthday;
    
            @Pattern(regexp = "^(.+)@(.+)$", message = "邮箱的格式不合法")
            private String email;
    
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            public String getAddress() {
                return address;
            }
    
            public void setAddress(String address) {
                this.address = address;
            }
    
            public BigDecimal getWeight() {
                return weight;
            }
    
            public void setWeight(BigDecimal weight) {
                this.weight = weight;
            }
    
            public String getFriendName() {
                return friendName;
            }
    
            public void setFriendName(String friendName) {
                this.friendName = friendName;
            }
    
            public Date getBirthday() {
                return birthday;
            }
    
            public void setBirthday(Date birthday) {
                this.birthday = birthday;
            }
    
            public String getEmail() {
                return email;
            }
    
            public void setEmail(String email) {
                this.email = email;
            }
        }
    
    

    DemoTest:

    import javax.validation.*;
    import java.math.BigDecimal;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.Set;
    
    public class DemoTest {
            public static void main(String[] args) {
                Student xiaoming = getBean();
                List<String> validate = validate(xiaoming);
                validate.forEach(row -> {
                    System.out.println(row.toString());
                });
    
            }
    
            private static Student getBean() {
                Student bean = new Student();
                bean.setName(null);
                bean.setAddress("北京");
                bean.setBirthday(new Date());
                bean.setFriendName(null);
                bean.setWeight(new BigDecimal(30));
                bean.setEmail("xiaogangfan163.com");
                return bean;
            }
    
            private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    
            public static <T> List<String> validate(T t) {
                Validator validator = factory.getValidator();
                Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);
    
                List<String> messageList = new ArrayList<>();
                for (ConstraintViolation<T> constraintViolation : constraintViolations) {
                    messageList.add(constraintViolation.getMessage());
                }
                return messageList;
            }
        }
    
    
    
    2.SpringMVC中的应用:

    实体类的注解还是和Student类一样,只是controller接值的时候需要做点改动如下:

    // 使用@Valid 表明获取到的数据模型需要验证,传入的Errors对象就是验证出错之后的数据对象,包括校验错误的个数,具体的信息等
    @RequestMapping(value="/register", method=RequestMethod.POST)
    public String registerForm(
            @Valid @ModelAttribute Student stu, Errors error){
        logger.info("注册新用户");
        
        if ( error.hasErrors()) {
            logger.error("出错啦");
        }
        
        stuList.add(stu);
        logger.info("注册的用户信息:/n" + stu);
        
        return "login";
    }
    
    
    
  • 相关阅读:
    Linux中常用的关机和重新启动命令
    Ubuntu 7.10 J2EE开发环境lomboz+eclipse3.2.1+tomcat5.5.25+mysql5.
    Linux+Apache+JSP+PHP+MySQL
    SMSLib的配置
    Python正则表达式操作指南
    Ubuntu学习笔记:通过ssh远程登录服务器
    C语言文件读写:语言初学者入门讲座 第十六讲 文件
    linuxfopenfclosefreadfwrite等函数
    linux 下 scp 的用法
    wget3
  • 原文地址:https://www.cnblogs.com/charlypage/p/9385146.html
Copyright © 2011-2022 走看看