SpringBoot项目使用Hibernate Validator进行表单验证

Posted nuist__NJUPT

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot项目使用Hibernate Validator进行表单验证相关的知识,希望对你有一定的参考价值。

SpringBoot项目使用Hibernate Validator进行表单验证

使用Hibernate Validator验证表单信息,具体要求入下:
(1)用户名必须输入,并且长度范围为5~20
(2)年龄范围在18~60
(3)工作日期在系统日期之前

1-创建Maven项目,并在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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>Thymeleaf</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <!--配置SpringBoot的核心启动器-->
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
    </parent>
    <dependencies>
    <dependency>
        <!--添加starter模块-->
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    </dependencies>

</project>

2-在src/main/java目录下创建com.model包,在该包中创建实体模型类,并在该类中进行注解验证。

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;
import org.springframework.format.annotation.DateTimeFormat;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Past;
import java.util.Date;

public class People {
    @NotBlank(message = "用户名必须输入")
    @Length(min = 5, max = 20, message = "用户名长度范围在5~20之间 ")
    private String username ;
    @Range(min = 18, max = 60, message = "年龄范围在18~60之间")
    private int age ;
    @Past(message = "当前日期必须在系统日期之前")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date date ;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

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

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

3-在src/main/java目录下创建com.controller包,在该包中创建控制器类,在控制器类中有两个方法,一个初始化方法,一个添加请求处理方法。

import com.model.People;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class TestValidator {
    @RequestMapping("/test")
    public String test(@ModelAttribute("peopleInfo")People people){ //初始化页面方法
        return "test" ;
    }
    @RequestMapping("/addUser")
    public String add(@ModelAttribute("peopleInfo") @Validated  People people, BindingResult result){
        if(result.hasErrors()){
            return "test" ; //验证失败
        }
        return "test1" ; //验证成功,跳到test1.html页面
    }
}

4-在src/main/resources/templates目录下创建视图页面test.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>表单验证页面</title>
    <link rel = "stylesheet" th:href = "@{css/bootstrap.min.css}"/>
    <link rel = "stylesheet" th:href = "@{css/bootstrap-theme.min.css}"/>
</head>
<body>
<div class = "panel panel-primary">
    <div class = "panel-heading">
        <h3 class = "panel-title">数据验证</h3>
    </div>
</div>
<div class = "container">
    <div>
        <h4>添加用户</h4>
    </div>
    <div class = "row">
        <div class = "col-md-6 col-sm-6">
            <form th:action="@{/addUser}" th:object="${peopleInfo}" method="post">
                <div class="form-group">
                    <div class="input-group col-md-6">
                <span class = "input-group-addon">
                    <i class = "glyphicon glyphicon-pencil"></i>
                </span>
                        <input class="form-control" type = "text"  th:placeholder="请输入用户名" th:field = "*{username}"/>
                        <span th:errors = "*{username}"></span>
                    </div>
                </div>
                <div class = "form-group">
                    <div class = "input-group col-md-6">
                <span class = "input-group-addon">
                      <i class = "glyphicon glyphicon-pencil"></i>
                </span>
                        <input class="form-control" type="text"  th:placeholder = "请输入年龄" th:field = "*{age}"/>
                        <span th:errors = "*{age}"></span>
                    </div>
                </div>
                <div class = "form-group">
                    <div class = "input-group col-md-6">
                <span class = "input-group-addon">
                      <i class = "glyphicon glyphicon-pencil"></i>
                </span>
                        <input class="form-control" type="text"   th:placeholder = "请输入日期" th:field = "*{date}"/>
                        <span th:errors = "*{date}"></span>
                    </div>
                </div>
                <div class = "form-group">
                    <div class = "col-md-6">
                        <div class = "btn-group btn-group-justified">
                            <div class = "btn-group">
                                <button type="submit"  class = "btn btn-success">
                                    <span class =  "glyphicon glyphicon-share"></span>
                                    &nbsp;添加
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>

5-在src/main/java目录下创建包com.test,在该包中创建启动类,运行启动类。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = {"com"})
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args) ;
    }
}

访问http://localhost:8080/test地址,并输入错误信息,点击添加,如下图所示:

以上是关于SpringBoot项目使用Hibernate Validator进行表单验证的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot项目使用Hibernate Validator进行表单验证

Spring boot第一个项目 Springboot + mysql + hibernate

springboot项目javax.validation使用

SpringBoot和Hibernate整合

在 Spring Boot 项目中使用 HikariCP 和 Hibernate 的更好方法

spring boot + hibernate 在我获得带有命名查询的项目后,我可以使用 entityMnager.persist(item) 吗?