`

59. Spring Boot Validator校验【从零开始学Spring Boot】

阅读更多

 

 

大纲:

(1) 入门例子;

(2) 国际化;

(3) 在代码中添加错误信息;

 

(1) 入门例子;

       Validator主要是校验用户提交的数据的合理性的,比如是否为空了,密码长度是否大于6位,是否是纯数字的,等等。那么在spring boot怎么使用这么强大的校验框架呢。

在这里我们主要是使用注解进行学习。我们先说说我们的需求:

我们有一个demo.html,在页面上有两个元素 姓名输入框,密码输入库,提交按钮。

提交到后台之后,使用Validator进行校验,然后如果存在错误,转发到demo.html,

我们先编写一个实体类接收用户的输入,以及使用Validator注解校验:

package com.kfit.demo;

 

import org.hibernate.validator.constraints.Length;

import org.hibernate.validator.constraints.NotEmpty;

 

public class Demo {

   

    private long id;

   

    @NotEmpty(message="姓名不能为空")

    private String name;

   

    @NotEmpty(message="密码不能为空")

    @Length(min=6,message="密码长度不能小于6")

    private String password;

 

    publiclong getId() {

       return id;

    }

 

    publicvoid setId(longid) {

       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;

    }

 

    @Override

    public String toString() {

       return "Demo [id=" + id + ", name=" + name + ", password=" + password + "]";

    }

}

这个实体类在属性上加入了注解@NotEmpty@Length,那么常用的注解有:

约束注解名称      约束注解说明

@null           验证对象是否为空

@notnull     验证对象是否为非空

@asserttrue       验证 boolean 对象是否为 true

@assertfalse      验证 boolean 对象是否为 false

@min           验证 number string 对象是否大等于指定的值

@max           验证 number string 对象是否小等于指定的值

@decimalmin    验证 number string 对象是否大等于指定的值,小数存在精度

@decimalmax    验证 number string 对象是否小等于指定的值,小数存在精度

@size           验证对象(array,collection,map,string)长度是否在给定的范围之内

@digits       验证 number string 的构成是否合法

@past           验证 date calendar 对象是否在当前时间之前

@future       验证 date calendar 对象是否在当前时间之后

@pattern     验证 string 对象是否符合正则表达式的规则

@Email     验证邮箱

 

实际例子:

@size (min=3, max=20, message="用户名长度只能在3-20之间")

@size (min=6, max=20, message="密码长度只能在6-20之间")

@pattern (regexp="[a-za-z0-9._%+-]+@[a-za-z0-9.-]+\\.[a-za-z]{2,4}", message="邮件格式错误")

@Length(min = 5, max = 20, message = "用户名长度必须位于520之间")  

@Email(message = "比如输入正确的邮箱")  

@NotNull(message = "用户名称不能为空") 
@Max(value = 100, message = "年龄不能大于100") 
@Min(value= 18 ,message= "必须年满18岁!"
 @AssertTrue(message = "bln4 must is true")

 

 @AssertFalse(message = "blnf must is falase")
@DecimalMax(value="100",message="decim最大值是100")
DecimalMin(value="100",message="decim最小值是100")
@NotNull(message = "身份证不能为空") 
@Pattern(regexp="^(\\d{18,18}|\\d{15,15}|(\\d{17,17}[x|X]))$", message="身份证格式错误")

 

好了,这个不是我们这节的重点,这里简单说一下而已,那么之后我们应该怎么做呢?我们需要编写一个Controller进行访问的时候,能访问到demo.html已经点击提交按钮的处理方法,具体看如下代码:

    @RequestMapping("/demo")

    public String demo(Model model){

       model.addAttribute("demo",new Demo());

       return "/demo";

    }

   

   

    @RequestMapping("/demoAdd")

    public String demoAdd(@Valid Demo demo,BindingResult result,Model model){

       //有错误信息.

       model.addAttribute("demo",demo);

       if(result.hasErrors()){

           List<ObjectError>  list = result.getAllErrors();

           for(ObjectError  error:list){

           System.out.println(error.getCode()+"---"+error.getArguments()+"---"+error.getDefaultMessage());

           }

          

           return "demo";

       }

       return "/demo";

    }

这里的代码还是需要简单说明下,我们使用@Valid指定要校验的实体类。

BindingResult  所有的错误信息都会保存在这个类中,我们可以使用result.hasErrors()  判断是否有错误信息,有的话,我么转发到我们原先的访问的hello.html,如果没有的话,我们正常应该是调整到list.html之类的,这里只是为了方便测试跳回了demo.html,但是如果没有任何错误信息的话,那么在页面上是不会显示错误信息的。

       好了,接下里我们看看demo.html是怎么编写的吧?

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8" />

    <title>hello spring boot</title>

</head>

<body>

   

    <form action="/demoAdd" method="post" th:object="${demo}">

       <p>姓名:<input type="text" name="name" th:value="*{name}" />

       </p>

       <p th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</p>

       <p>密码:<input type="text" name="password" th:value="*{password}"  />

       </p>

       <p th:if="${#fields.hasErrors('password')}" th:errors="*{password}">password Error</p>

       <p><button>提交</button></p>

    </form>

</body>

</html>

这里我们使用的thymeleaf进行展示数据的,使用jsp的代码需要用到tag标签,也能实现相同的效果,自行百度学习。这里核心代码就是:

<p th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</p>

这句代码一旦后台有返回异常信息的话,就会显示name对应的message,如果满足了两个条件的话,是会返回两个的,之间是用<br/>进行处理的,就如我们的password什么都不填写的情况下是会显示如下信息的:

密码:

密码不能为空
      
密码长度不能小于6

 

 

(2) 国际化;

       在上一节我们就讲过国际化了,那么如何在Validator加入国际化呢,很简单的,只需要在国际化配置文件加入相应的配置如:

demo.name = `name` is not empty.

这里需要注意的地方是:

必须放在classes目录下,而且必须用ValidationMessages这个名字

也就是文件名称需要命令为:

ValidationMessages.properties

ValidationMessages_en.properties

 

那么修改Demo.java文件:

@NotEmpty(message="{demo.name}")

 

(3) 在代码中添加错误信息;

       有些代码是很难使用Validator的注解来实现的,那么我们怎们在返回的信息添加我们自己的判断呢,比如我们现在要求用户输入的name不能重复,那么势必我们会这么一段代码: 如果存在name,那么返回“该name已经存在了”。其实这个也是很简单,只需要一句话代码就可以添加自定义错误字段的信息了:

result.rejectValue("name", "misFormat", "这个name已经注册过了!");

 

当然在添加的时候,外层应该有一个if(isExist(“name”))这样的代码,这里没有进行编写,就直接添加了,实际开发请自行从数据库获取,然后进行判断。

  

Spring Boot 系列博客】

à悟空学院:https://t.cn/Rg3fKJD

学院中有Spring Boot相关的课程!点击「阅读原文」进行查看!

SpringBoot视频:http://t.cn/A6ZagYTi

Spring Cloud视频:http://t.cn/A6ZagxSR

SpringBoot Shiro视频:http://t.cn/A6Zag7IV

SpringBoot交流平台:https://t.cn/R3QDhU0

SpringData和JPA视频:http://t.cn/A6Zad1OH

SpringSecurity5.0视频:http://t.cn/A6ZadMBe

Sharding-JDBC分库分表实战http://t.cn/A6ZarrqS

分布式事务解决方案「手写代码」:http://t.cn/A6ZaBnIr

 

网易云课堂视频最新更新

第十一章 Spring Boot 日志

1、spring boot日志—理论

2、Spring Boot日志-logback

3、Spring Boot日志-log4j2

第十二章 Spring Boot 知识点2

1、spring boot 服务配置和部署

2、Spring Boot 定制URL匹配规则

 

 

历史章节

 

第一章 快速开始

1、Spring Boot之Hello World

2、Spring Boot之Hello World访问404

 

第二章 Spring Boot之JSON

1、spring boot返回json数据

2、Spring Boot完美使用FastJson解析JSON数据

 

第三章 Spring Boot热部署

1、Spring Boot热部署(springloader)

2、springboot + devtools(热部署)

 

第四章 Spring Boot数据库

1、Spring Boot JPA/Hibernate/Spring Data概念

2、Spring Boot JPA-Hibernate

3、Spring Boot Spring Data JPA介绍

4、Spring Boot JdbcTemplate

5、Spring Boot集成MyBatis

 

第五章 web开发

1、全局异常捕捉

2、配置server信息

3、spring boot使用thymeleaf

4、Spring Boot 使用freemarker

5、Spring Boot添加JSP支持

 

第六章 定时任务

1、Spring Boot定时任务

2、Spring Boot 定时任务升级篇(动态修改cron参数)

3、Spring Boot 定时任务升级篇(动态添加修改删除定时任务)

4、Spring Boot 定时任务升级篇(集群/分布式下的定时任务说明)

5、Spring Boot Quartz介绍

6、Spring Boot Quartz在Java Project中使用

7、Spring Boot 集成Quartz普通使用

8、Spring Boot 集成Quartz升级版

9、Spring Boot 集成Quartz二次升级版

10、Spring Boot 集成Quartz-Job如何自动注入Spring容器托管的对象

 

第七章 Spring Boot MyBatis升级篇

1、Spring Boot MyBatis升级篇-注解

2、Spring Boot MyBatis升级篇-注解-自增ID

3、Spring Boot MyBatis升级篇-注解-增删改查

4、Spring Boot MyBatis升级篇-注解-分页查询

5、Spring Boot MyBatis升级篇-注解-分页PageHelper不生效

6、Spring Boot MyBatis升级篇-注解- mybatic insert异常:BindingException: Parameter 'name' not found

7、Spring Boot MyBatis升级篇-注解- #和$符号特别篇

8、Spring Boot MyBatis升级篇-注解-@Result

9、Spring Boot MyBatis升级篇-注解-动态SQL(if test)-方案一:<script>

10、Spring Boot MyBatis升级篇-注解-动态SQL(if test)-方案二:@Provider

11、Spring Boot MyBatis升级篇-注解-动态SQL-参数问题

12、Spring Boot MyBatis升级篇-注解-特别篇:@MapperScan和@Mapper

13、Spring Boot MyBatis升级篇-XML

14、Spring Boot MyBatis升级篇-XML-自增ID

15、Spring Boot MyBatis升级篇-XML-增删改查

16、Spring Boot MyBatis升级篇-XML-分页查询

17、Spring Boot MyBatis升级篇-XML-分页PageHelper不生效

18、Spring Boot MyBatis升级篇-XML-动态SQL(if test)

19、Spring Boot MyBatis升级篇-XML-注解-初尝试

20、Spring Boot MyBatis升级篇- pagehelper替换为pagehelper-spring-boot-starter

 

第八章 Spring Boot 知识点1

1、Spring Boot 拦截器HandlerInterceptor

2、Spring Boot启动加载数据CommandLineRunner

3、Spring Boot环境变量读取和属性对象的绑定

4、Spring Boot使用自定义的properties

5、Spring Boot使用自定义的properties

6、Spring Boot使用@SpringBootApplication

7、Spring Boot 监控和管理生产环境

 

第十章 Spring Boot 打包部署

1、Spring Boot打包部署((提供Linux的sh文件))

 

第十一章 Spring Boot 日志

1、spring boot日志—理论

2、Spring Boot日志-logback

 

3、Spring Boot日志-log4j2

更多查看博客: http://412887952-qq-com.iteye.com/

分享到:
评论
6 楼 林祥纤 2018-02-12  
jaingbei 写道
请问所有的校验的注解在哪可以找到,谢谢


上官方网站
5 楼 jaingbei 2018-02-09  
请问所有的校验的注解在哪可以找到,谢谢
4 楼 林祥纤 2017-09-16  
qq294761842 写道
后台通过
result.addError(new ObjectError("xxx","xxxxxx"));

result.rejectValue("xxx", "xxxx", "xxxxxxx");
添加的错误信息,thymeleaf前台怎么显示?我现在碰到的问题是通过th:each能输出所有错误,包括后添加的错误,但是我想将错误信息显示在每个项目后面,使用下面方式出错,该如何输出呢?

<span class="red" th:if="${#fields.hasErrors('xxx')}" th:text="${xx}"></span>


这个应该是可以的!
3 楼 qq294761842 2017-09-15  
后台通过
result.addError(new ObjectError("xxx","xxxxxx"));

result.rejectValue("xxx", "xxxx", "xxxxxxx");
添加的错误信息,thymeleaf前台怎么显示?我现在碰到的问题是通过th:each能输出所有错误,包括后添加的错误,但是我想将错误信息显示在每个项目后面,使用下面方式出错,该如何输出呢?

<span class="red" th:if="${#fields.hasErrors('xxx')}" th:text="${xx}"></span>
2 楼 林祥纤 2017-08-14  
aistxbb 写道
请问,我想允许某个字段可以不填,但台果填写,那么值必须保持一种特定的格式,请问这种情况怎么实现呢?


目前想到的方案是:
if(name != null){
   //进行判断,不满足条件就返回.
   result.rejectValue("name", "misFormat", "对不起,输入有误");
}
1 楼 aistxbb 2017-08-13  
请问,我想允许某个字段可以不填,但台果填写,那么值必须保持一种特定的格式,请问这种情况怎么实现呢?

相关推荐

Global site tag (gtag.js) - Google Analytics