上一节刚刚讲解了,如何通过Thymeleaf 来使用表单提交,现在我们这一节,讲解如何使用表单验证。Thymeleaf 表单验证的步骤:1、添加hibernate-validator的依赖包。2、创建表单类,里面添加注解说明字段的信息,3、创建界面控制器,里面需要通过注解@ModelAttribute("userInfo")标明,表单类对象。4、创建界面模板,用于接收模板的信息,5、表单处理控制器,处理表单的请求,这个方法里面,必须同界面控制器一样,通过注解@ModelAttribute("userInfo")标明,表单类对象,这样保证获取的对象在出现错误,能直接返回到界面,如果注解不标明,就找不到表单对象,界面就会报错了。6、测试代码。

代码地址

https://gitee.com/yellowcong/springboot-thymeleaf/tree/master/chapter3/springboot-thymeleaf1

jar包导入

spring-boot-starter-web包里面有hibernate-validator包,不需要引用hibernate validator依赖。

<!-- 导入hibernate验证包 -->
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-validator</artifactId>
</dependency>

Springboot之Thymeleaf 表单标签(表单验证)|第三章-yellowcong_表单

验证注解

下面是我直接复制贴过来的注解说明,需要注意一点的是,有些注解只能用在数字上才生效,有些注解是用在字符串上的。

JSR提供的校验注解:         
@Null           被注释的元素必须为 null    
@NotNull        被注释的元素必须不为 null    
@AssertTrue     被注释的元素必须为 true    
@AssertFalse    被注释的元素必须为 false    
@Min(value)     被注释的元素必须是一个数字,其值必须大于等于指定的最小值    
@Max(value)     被注释的元素必须是一个数字,其值必须小于等于指定的最大值    
@DecimalMin(value)  被注释的元素必须是一个数字,其值必须大于等于指定的最小值    
@DecimalMax(value)  被注释的元素必须是一个数字,其值必须小于等于指定的最大值    
@Size(max=, min=)   被注释的元素的大小必须在指定的范围内    
@Digits (integer, fraction)     被注释的元素必须是一个数字,其值必须在可接受的范围内    
@Past   被注释的元素必须是一个过去的日期    
@Future     被注释的元素必须是一个将来的日期    
@Pattern(regex=,flag=)  被注释的元素必须符合指定的正则表达式    


Hibernate Validator提供的校验注解:  
@NotBlank(message =)   验证字符串非null,且长度必须大于0    
@Email  被注释的元素必须是电子邮箱地址    
@Length(min=,max=)  被注释的字符串的大小必须在指定的范围内    
@NotEmpty   被注释的字符串的必须非空    
@Range(min=,max=,message=)  被注释的元素必须在合适的范围内

表单验证

1、表单模型

这个表单对象,我采用了lombok 的jar包,通过注解的方式生成set和get方式,简化代码了,和普通的表单类是一毛一样的,别太惊讶。

package com.yellowcong.form;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

import lombok.Getter;
import lombok.Setter;

/**
 * 创建日期:2018年4月5日<br/>
 * 代码创建:黄聪<br/>
 * 功能描述:表单信息<br/>
 */
@Setter
@Getter
public class UserForm {
    @NotEmpty(message="用户名不能为空")
    @Length(min = 2, max = 32, message = "用户名长度在2到32个字符之间")
    private String username;

    @NotEmpty(message="密码不能为空")
    @Length(min = 6, max = 32, message = "密码长度在6到32个字符之间")
    private String password;

}

2、界面控制器

可以看到,我们的form的表单的对象,直接注入到request里面了

/**
 * 创建日期:2018年4月5日<br/>
 * 代码创建:黄聪<br/>
 * 功能描述:首页模版<br/>
 * @return
 */
@RequestMapping("/index")
public String index(@ModelAttribute("userInfo") UserForm user){
    //设定model值
    user.setPassword("test_ps");
    user.setUsername("test");

    return "admin/index";
}

3、界面模板

界面模板中,直接读取到ModelAttribute里面注入的数据,然后可以通过th:if="${#fields.hasErrors('password')}" th:errors="*{password}" 获取返回信息。

<!DOCTYPE html>
<!-- 需要添加
<html  xmlns:th="http://www.thymeleaf.org">
这样在后面的th标签就不会报错
 -->
<html  xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title th:text="${username}">xx</title>
</head>
<body>
<h1 th:text="${username}">Hello World</h1>
<h1>获取对象信息</h1>
<h2>1、通过直接访问对象的方式</h2>
<p th:text="${userInfo.username}"></p>
<p th:text="${userInfo.password}"></p>


<h2>2、通过th:object访问对象的方式</h2>
<div th:object="${userInfo}">
    <p th:text="*{username}"></p>
    <p th:text="*{password}"></p>
</div>

<h1>表单提交</h1>
<!-- 表单提交用户信息,注意字段的设置,直接是*{} -->
 <form action="#" th:action="@{/add}" th:object="${userInfo}" method="post">  
  <div><span>用户名</span><input type="text" th:field="*{username}" />  <span th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></span></div>
  <div><span>密码</span><input type="text" th:field="*{password}" />  <span th:if="${#fields.hasErrors('password')}" th:errors="*{password}"></span></div>
  <input type="submit" />  
</form> 
</body>
</html>

4、请求处理控制器

控制器中,如果存在错误的情况,直接返回到添加的界面,如果添加成功了,也是反回到添加界面。

/**
* 创建日期:2018年4月6日<br/>
 * 代码创建:黄聪<br/>
 * 功能描述:处理add请求<br/>
 * @param user
 * @return
 */
@RequestMapping(value="/add",method=RequestMethod.POST)
public String add(@ModelAttribute("userInfo") @Validated UserForm user,BindingResult rs){
    if(rs.hasErrors()){
           for (ObjectError error : rs.getAllErrors()) {
               System.out.println(error.getDefaultMessage());
           }
           return "admin/index";
       }

    //验证成功,我们可以返回到自己想去的界面了,我这个地方直接返回到添加的界面
    return "admin/index";
}

5、测试

我输入用户名为空的时候,就提示错了,然后输入的字段少,也提示错误了,然后我输入正确了数据后,直接跳转到添加页面,然后显示我刚刚添加的数据。

Springboot之Thymeleaf 表单标签(表单验证)|第三章-yellowcong_表单_02