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地址,并输入错误信息,点击添加,如下图所示:
在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nuist__NJUPT

给个鼓励吧,谢谢你

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值