spring boot

Spring Boot Validating 校验请求参数

2019-04-23  本文已影响290人  又语

本文介绍 Spring Boot 2 校验 Web 应用请求参数有效性的方法。


目录


javax.validation.constraints 介绍

javax.validation.constraints 包含所有 Bean Validation 提供的约束,又称为内置约束。参考最新的 Java(TM) EE 7 Specification APIs,共提供 13 个注解类:


开发环境


基础示例

  1. 创建 Spring Boot 工程,参考:IntelliJ IDEA 创建 Spring Boot 工程

  2. 生成的 pom 文件如下,注意需要添加 spring-boot-starter-weborg.hibernate.validator:hibernate-validator 依赖。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>tutorial.spring.boot</groupId>
    <artifactId>spring-boot-validating</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-validating</name>
    <description>Spring Boot Validating</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.16.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
  1. 创建实体类(领域模型)。
package tutorial.spring.boot.validating.domain;

import javax.validation.constraints.*;
import java.util.Date;

public class User {

    @NotNull(message = "姓名不能为空")
    @Size(min = 2, max = 20, message = "不满足姓名长度要求:2~20")
    private String name;

    @NotNull(message = "年龄不能为空")
    @Max(value = 16, message = "不满足最大年龄16岁")
    private Integer age;

    @Min(value = 150, message = "不满足最小身高1米5")
    private Double height;

    @Pattern(regexp = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$", message = "不满足邮箱正则表达式")
    private String email;

    @Past(message = "出生日期非法")
    private Date birth;

    @AssertTrue(message = "不满足会员要求")
    private Boolean member;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Double getHeight() {
        return height;
    }

    public void setHeight(Double height) {
        this.height = height;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Boolean getMember() {
        return member;
    }

    public void setMember(Boolean member) {
        this.member = member;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", height=" + height +
                ", email='" + email + '\'' +
                ", birth=" + birth +
                ", member=" + member +
                '}';
    }
}
  1. 编写校验请求的接口。
package tutorial.spring.boot.validating.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tutorial.spring.boot.validating.domain.User;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/")
public class UserController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @InitBinder
    protected void init(HttpServletRequest request, ServletRequestDataBinder binder) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        format.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format, false));
    }

    @PostMapping
    public String validateUser(@Valid User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            bindingResult.getAllErrors().forEach(error -> LOGGER.error(error.getDefaultMessage()));
            return "User is invalid: " + user;
        }
        return "User is valid: " + user;
    }
}

注意:@InitBinder 注解的 init 方法是用来处理 java.util.Date 类型转换的(String 转 Date)。

  1. 启动后使用 Postman 测试。

控制台打印日志如下:

2019-04-23 21:09:20.362 ERROR 13380 --- [nio-8080-exec-2] t.s.b.v.controller.UserController        : 出生日期非法
2019-04-23 21:09:20.362 ERROR 13380 --- [nio-8080-exec-2] t.s.b.v.controller.UserController        : 不满足邮箱正则表达式
2019-04-23 21:09:20.362 ERROR 13380 --- [nio-8080-exec-2] t.s.b.v.controller.UserController        : 不满足最大年龄16岁
2019-04-23 21:09:20.362 ERROR 13380 --- [nio-8080-exec-2] t.s.b.v.controller.UserController        : 不满足会员要求
2019-04-23 21:09:20.362 ERROR 13380 --- [nio-8080-exec-2] t.s.b.v.controller.UserController        : 不满足最小身高1米5
2019-04-23 21:09:20.362 ERROR 13380 --- [nio-8080-exec-2] t.s.b.v.controller.UserController        : 不满足姓名长度要求:2~20

总结

源码:https://gitee.com/jyl1626938665/spring-tutorial/tree/master/spring-boot-tutorial/spring-boot-validating

上一篇下一篇

猜你喜欢

热点阅读