SpringMVC学习系列(6) 之 数据验证
在系列(4)、(5)中我们展示了如何绑定数据,绑定完数据之后如何确保我们得到的数据的正确性?这就是我们本篇要说的内容 —> 数据验证。
这里我们采用Hibernate-validator来进行验证,Hibernate-validator实现了JSR-303验证框架支持注解风格的验证。首先我们要到http://hibernate.org/validator/下载需要的jar包,这里以4.3.1.Final作为演示,解压后把hibernate-validator-4.3.1.Final.jar、jboss-logging-3.1.0.jar、validation-api-1.0.0.GA.jar这三个包添加到项目中。
配置之前项目中的springservlet-config.xml文件,如下:
<!-- 默认的注解映射的支持 --> <mvc:annotation-driven validator="validator" conversion-service="conversion-service" /><bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"><property name="providerClass" value="org.hibernate.validator.HibernateValidator"/><!--不设置则默认为classpath下的 ValidationMessages.properties --><property name="validationMessageSource" ref="validatemessageSource"/></bean><bean id="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" /><bean id="validatemessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="classpath:validatemessages"/> <property name="fileEncodings" value="utf-8"/> <property name="cacheSeconds" value="120"/> </bean>
其中<property name=”basename” value=”classpath:validatemessages”/>中的classpath:validatemessages为注解验证消息所在的文件,需要我们在resources文件夹下添加。
在com.demo.web.controllers包中添加一个ValidateController.java内容如下:
package com.demo.web.controllers;import java.security.NoSuchAlgorithmException; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.demo.web.models.ValidateModel;@Controller @RequestMapping(value = "/validate") public class ValidateController {@RequestMapping(value="/test", method = {RequestMethod.GET})public String test(Model model){if(!model.containsAttribute("contentModel")){model.addAttribute("contentModel", new ValidateModel());}return "validatetest";}@RequestMapping(value="/test", method = {RequestMethod.POST})public String test(@Valid @ModelAttribute("contentModel") ValidateModel validateModel, BindingResult result, Model model) throws NoSuchAlgorithmException{//如果有验证错误 返回到form页面if(result.hasErrors())return test(model);return "validatesuccess"; }}
其中@Valid @ModelAttribute(“contentModel”) ValidateModel validateModel的@Valid 意思是在把数据绑定到@ModelAttribute(“contentModel”) 后就进行验证。
在com.demo.web.models包中添加一个ValidateModel.java内容如下:
package com.demo.web.models;import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.Range;public class ValidateModel{@NotEmpty(message="{name.not.empty}")private String name;@Range(min=0, max=150,message="{age.not.inrange}")private String age;@NotEmpty(message="{email.not.empty}")@Email(message="{email.not.correct}")private String email;public void setName(String name){this.name=name;}public void setAge(String age){this.age=age;}public void setEmail(String email){this.email=email;}public String getName(){return this.name;}public String getAge(){return this.age;}public String getEmail(){return this.email;}}
在注解验证消息所在的文件即validatemessages.properties文件中添加以下内容:
name.not.empty=\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A\u3002 age.not.inrange=\u5E74\u9F84\u8D85\u51FA\u8303\u56F4\u3002 email.not.correct=\u90AE\u7BB1\u5730\u5740\u4E0D\u6B63\u786E\u3002 email.not.empty=\u7535\u5B50\u90AE\u4EF6\u4E0D\u80FD\u60DF\u6050\u3002
其中name.not.empty等分别对应了ValidateModel.java文件中message=”xxx”中的xxx名称,后面的内容是在输入中文是自动转换的ASCII编码,当然你也可以直接把xxx写成提示内容,而不用另建一个validatemessages.properties文件再添加,但这是不正确的做法,因为这样硬编码的话就没有办法进行国际化了。
在views文件夹中添加validatetest.jsp和validatesuccess.jsp两个视图,内容分别如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body><form:form modelAttribute="contentModel" method="post"> <form:errors path="*"></form:errors><br/><br/>name:<form:input path="name" /><br/><form:errors path="name"></form:errors><br/>age:<form:input path="age" /><br/><form:errors path="age"></form:errors><br/>email:<form:input path="email" /><br/><form:errors path="email"></form:errors><br/><input type="submit" value="Submit" /></form:form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body>验证成功! </body> </html>
其中特别要指出的是validatetest.jsp视图中<form:form modelAttribute=”contentModel” method=”post”>的modelAttribute=”xxx”后面的名称xxx必须与对应的@Valid @ModelAttribute(“xxx”) 中的xxx名称一致,否则模型数据和错误信息都绑定不到。
<form:errors path=”name”></form:errors>即会显示模型对应属性的错误信息,当path=”*”时则显示模型全部属性的错误信息。
运行测试:
直接点击提交:
可以看到正确显示了设置的错误信息。
填写错误数据提交:
可以看到依然正确显示了设置的错误信息。
填写正确数据提交:
可以看到验证成功。
下面是主要的验证注解及说明:
注解 |
适用的数据类型 |
说明 |
@AssertFalse |
Boolean, boolean |
验证注解的元素值是false |
@AssertTrue |
Boolean, boolean |
验证注解的元素值是true |
@DecimalMax(value=x) |
BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence. |
验证注解的元素值小于等于@ DecimalMax指定的value值 |
@DecimalMin(value=x) |
BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence. |
验证注解的元素值小于等于@ DecimalMin指定的value值 |
@Digits(integer=整数位数, fraction=小数位数) |
BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence. |
验证注解的元素值的整数位数和小数位数上限 |
@Future |
java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant. |
验证注解的元素值(日期类型)比当前时间晚 |
@Max(value=x) |
BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type ofCharSequence (the numeric value represented by the character sequence is evaluated), any sub-type of Number. |
验证注解的元素值小于等于@Max指定的value值 |
@Min(value=x) |
BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of CharSequence (the numeric value represented by the char sequence is evaluated), any sub-type of Number. |
验证注解的元素值大于等于@Min指定的value值 |
@NotNull |
Any type |
验证注解的元素值不是null |
@Null |
Any type |
验证注解的元素值是null |
@Past |
java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant. |
验证注解的元素值(日期类型)比当前时间早 |
@Pattern(regex=正则表达式, flag=) |
String. Additionally supported by HV: any sub-type of CharSequence. |
验证注解的元素值与指定的正则表达式匹配 |
@Size(min=最小值, max=最大值) |
String, Collection, Map and arrays. Additionally supported by HV: any sub-type of CharSequence. |
验证注解的元素值的在min和max(包含)指定区间之内,如字符长度、集合大小 |
@Valid |
Any non-primitive type(引用类型) |
验证关联的对象,如账户对象里有一个订单对象,指定验证订单对象 |
@NotEmpty |
|
验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0) |
@Range(min=最小值, max=最大值) |
|
验证注解的元素值在最小值和最大值之间 |
@NotBlank |
|
验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格 |
@Length(min=下限, max=上限) |
|
验证注解的元素值长度在min和max区间内 |
|
|
验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式 |
更多信息请参考官方文档:http://docs.jboss.org/hibernate/validator/4.3/reference/en-US/html/validator-usingvalidator.html
数据验证的内容到此结束,代码下载:http://pan.baidu.com/s/1pJDc12V
SpringMVC学习系列(6) 之 数据验证相关推荐
- Caffe学习系列(13):数据可视化环境(python接口)配置
原文有更新: Caffe学习系列(13):数据可视化环境(python接口)配置 - denny402 - 博客园 http://www.cnblogs.com/denny402/p/5088399. ...
- SpringMVC学习系列(5) 之 数据验证
原文地址 http://www.cnblogs.com/liukemng/p/3738055.html 这里我们采用Hibernate-validator来进行验证,Hibernate-validat ...
- SpringMVC学习系列(11) 之 表单标签
2019独角兽企业重金招聘Python工程师标准>>> 本篇我们来学习Spring MVC表单标签的使用,借助于Spring MVC提供的表单标签可以让我们在视图上展示WebMode ...
- Silverlight Telerik控件学习:数据录入、数据验证
相信很多人都听说过这句名言:garbage in ,garbage out ! 数据录入不规范(或错误)就象一颗定时炸弹,迟早会给系统带来麻烦,所以在数据录入时做好验证是很有必要的. 相对传统asp. ...
- 【Excel学习笔记6】数据验证是什么?如何使用?小缺陷?
一.数据验证? 提前设置好单元格格式,然后点击数据--数据验证,进行设置. 可以进行哪些数据验证呢?任何值.整数.小数.序列.日期.时间.文本长度.自定义. 还可以进行提示信息和出错警告的设置. 二. ...
- SpringMVC 学习系列 (4) 之 数据绑定 -1
2019独角兽企业重金招聘Python工程师标准>>> 在系列(3)中我们介绍了请求是如何映射到一个action上的,下一步当然是如何获取到请求中的数据,这就引出了本篇所要讲的内容- ...
- Scikit-learn学习系列 | 2. sklearn数据预处理的相关方法
如有错误,恳请指出. 以下内容整理自专栏:博主"文火冰糖的硅基工坊"的专栏--机器学习与scikit-learn,对部分的文章的简化与整理. 文章目录 1. 数据预处理介绍 2. ...
- SpringMVC 学习系列 (3) 之 URL请求到Action的映射规则
2019独角兽企业重金招聘Python工程师标准>>> 在系列(2)中我们展示了一个简单的get请求,并返回了一个简单的helloworld页面.本篇我们来学习如何来配置一个acti ...
- SpringMVC学习系列(六)------图片的上传
前言 在表单数据中,我们可能会遇到头像.照片等图片的上传等需求,那么如果表单中包含一个图片元素,我们在controller中应该如何接收呢? 正文 在实际的项目中,我们通常都会有专门的 ...
最新文章
- vscode中设置字体大小_vscode配置使用教程
- 对称加密算法_技术分享丨这是一篇简单的小科普——什么是对称加密算法?(下)...
- Hibernate getCurrentSession()和openSession()的区别
- 【C 语言】字符串操作 ( 使用 数组下标 操作字符串 | 使用 char * 指针 操作字符串 )
- Jenkins之构建Maven项目的多种方式
- boost::signals2::slot相关的测试程序
- 【ASP.NET】获取网站目录的方法
- macOS Unlocker3.0
- C语言和设计模式(外观模式)
- python三维圆曲面_python – matplotlib中的曲面和三维轮廓
- dbf如何导入oracle_克服Oracle导数一切难题
- RAID技术全解图解-RAID0、RAID1、RAID5、RAID100
- 整除光棍 — C语言【模拟手算除法(附过程图解)】
- 算法设计与分析第五章习题解答与学习指导(第2版)屈婉婷 刘田 张立昂 王捍贫编著 清华大学出版社
- 计算机如何连接隐藏的无线网络,笔记本电脑怎么连接隐藏的无线网wifi
- 【Mathematica】三种画爱心的方法
- 强大且免费的文本转换工具,word转其他格式,epub转换
- python与其他的数据分析有什么区别_学好python和数据分析有什么关系?
- 狼人杀服务器修改,微信小程序版狼人杀+服务端系列(1)
- 青岛新媒体运营教程:三步浅谈活动运营,拆解策划实施
热门文章
- 机器人动力学方程的四种形式
- silverlight 学习笔记 (一):silverlight 能做什么
- 【AI 技术精选】神经网络结构深入分析和比较
- 映客财报:翻身与社交突围
- ASEMI整流模块MDA110-16参数,MDA110-16规格
- window.postMessage - 前端跨域通信
- win7 系统增加自定义分辨率_【文献转载】GT5000便携式多参数土壤呼吸测量系统用于棉花田间土壤二氧化碳释放量的测量...
- win7 系统增加自定义分辨率_【文献转载】GT5000便携式多参数土壤呼吸测量系统用于冬小麦田间土壤氧化亚氮释放量的测量...
- 华为公有云认证培训认证体系- HCIA,HCIP ,HCIE
- Ktor: Kotlin Web后端框架 快速开始入门