第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";
}


posted @ 2018-07-29 13:51  城南少年与猫  阅读(493)  评论(0编辑  收藏  举报