Spring Boot表单数据验证

在Spring Boot中我们经常需要对表单数据进行合法性验证。下面讲解如何在Spring Boot中进行表单验证。

1 建立项目,导入依赖

<?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>com.yiidian</groupId>
    <artifactId>ch02_05_springboot_validation</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- 导入springboot父工程. 注意:任何的SpringBoot工程都必须有的!!! -->
    <!-- 父工程的作用:锁定起步的依赖的版本号,并没有真正到依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.11.RELEASE</version>
    </parent>

    <dependencies>
        <!--web起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 导入thymeleaf坐标 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>
</project>

2 设计Pojo,添加验证注解

package com.yiidian.domain;

import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.Email;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;

/**
 * 实体
 * 一点教程网 - www.yiidian.com
 */
public class User {

	private Integer id;
	//@NotBlank(message="用户名不能为空") // 非空
	@NotEmpty(message="用户名不能为空")
	private String name;
	@NotBlank(message="密码不能为空") // 非空
	@Length(min=4,max=10,message="密码必须在4-10位之间")
	private String password;
	@Min(value=0)
	private Integer age;
	@Email(message="邮箱不合法")
	private String email;
	
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	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;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", password=" + password + ", age=" + age + "]";
	}
	
}

3 编写Controller,处理错误

package com.yiidian.controller;

import com.yiidian.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;

/**
 * 控制器
 * 一点教程网 - www.yiidian.com
 */
@Controller
@RequestMapping("/user")
public class UserController {

    /**
     * 跳转到add.html
     * @return
     */
    @RequestMapping("toAdd")
    public String toAdd(User user){
        return "add";
    }

    /**
     * 用户添加
     * BindingResult: 用于封装验证对象(user)里面的验证结果
     */
    @RequestMapping("add")
    public String add(@Valid User user, BindingResult result){
        //如果存在验证错误
        if(result.hasErrors()){
            //返回add.html
            return "add";
        }

        System.out.println("保存用户:"+user);
        return "succ";
    }
}

4 设计页面,回显错误信息

add.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户添加</title>
</head>
<body>
<h3>用户添加</h3>
<form action="/user/add" method="post">
用户名:<input type="text" name="name"/><font color="red" th:errors="${user.name}"></font><br/>
密码:<input type="password" name="password"/><font color="red" th:errors="${user.password}"></font><br/>
年龄:<input type="text" name="age"/><font color="red" th:errors="${user.age}"></font><br/>
邮箱:<input type="text" name="email"/><font color="red" th:errors="${user.email}"></font><br/>
<input type="submit" value="保存"/>
</form>
</body>
</html>

list.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>提示页面</title>
</head>
<body>
保存成功
</body>
</html>

5 运行效果

源码下载:https://pan.baidu.com/s/1_h-rVDdQsOBs9VsJ4cUmtQ