SpringBoot數據校驗功能的實現

1.pom.xml

<?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 https://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.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yl</groupId>
    <artifactId>validation</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>validation</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
            <artifactId>spring-boot-starter-web</artifactId>

            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2.實體類,註意:可以不用加ValidationMessages.properties文件,可以直接在message=""地方直接寫上報錯信息

package com.yl.validation.model;
import com.yl.validation.validation.ValidationGroup1;
import com.yl.validation.validation.ValidationGroup2;
import javax.validation.constraints.*;
import java.io.Serializable;
public class User implements Serializable {
    private Integer id;
    //校驗字符串長度
    @Size(min = 3,max = 8,message = "{user.username.size}",groups = ValidationGroup1.class)
    private String username;
    //非空校驗
    @NotNull(message = "{user.password.notnull}")
    private String password;
    //數值范圍校驗
    @DecimalMin(value = "15",message = "{user.age.min}",groups = {ValidationGroup1.class, ValidationGroup2.class})
    @DecimalMax(value = "30",message = "{user.age.max}",groups = {ValidationGroup1.class, ValidationGroup2.class})
    private Integer age;
    //非空校驗
    @NotNull(message = "{user.email.notnull}")
    //郵箱格式校驗
    @Email(message = "{user.email.pattern}")
    private String email;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                '}';
    }
}

3.controller

package com.yl.validation.controller;

import com.yl.validation.model.User;
import com.yl.validation.validation.ValidationGroup1;
import com.yl.validation.validation.ValidationGroup2;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
    @PostMapping("/addUser")
    public void addUser(@Validated(ValidationGroup2.class) User user, BindingResult result) {
        if (result != null && result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError objectError : allErrors) {
                System.out.println(objectError.getDefaultMessage());
            }
        }
    }
}

4.ValidationMessages.Properties,手動新建放在resources目錄下

user.username.size=用戶名的長度應為3到8
user.password.notnull=密碼不能為空
user.age.min=年齡最小值為15
user.age.max=年齡最大值為30
user.email.notnull=郵箱不能為空
user.email.pattern=郵箱格式不正確

5.組一

package com.yl.validation.validation;

public interface ValidationGroup1 {
}

6.組二

package com.yl.validation.validation;

public interface ValidationGroup2 {
}

7.測試結果,由於分瞭組,發現隻有年齡校驗有效!

在這裡插入圖片描述

在這裡插入圖片描述

到此這篇關於SpringBoot數據校驗的文章就介紹到這瞭,更多相關SpringBoot數據校驗內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: