您的位置:首页 > 编程语言 > Java开发

SpringMVC学习系列(6) 之 数据验证

2015-10-23 17:41 651 查看


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(Model model, @Valid @ModelAttribute("contentModel") ValidateModel validateModel, BindingResult result) 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
CharSequence
,
Collection
,
Map and Arrays

验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)
@Range(min=最小值, max=最大值)
CharSequence, Collection, Map and Arrays,BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types

验证注解的元素值在最小值和最大值之间
@NotBlank
CharSequence

验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格
@Length(min=下限, max=上限)
CharSequence

验证注解的元素值长度在min和max区间内
@Email
CharSequence

验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式
更多信息请参考官方文档:http://docs.jboss.org/hibernate/validator/4.3/reference/en-US/html/validator-usingvalidator.html

数据验证的内容到此结束,代码下载:http://pan.baidu.com/s/1pJDc12V

注: 之前没注意前11篇的示例代码,不知道为什么当时打包上传上去的是没有.project项目文件的,导致下载后不能直接导入eclipse运行,虚拟机又 被我删掉了,这些示例代码也没有备份,但是代码文件还在的,所以可以新建一个Dynamic Web Project把对应的配置文件和controller还有view导入就可以了,给大家造成的不便说声抱歉。

分类: Spring MVC
标签: SpringMVC

好文要顶 关注我 收藏该文







Miss When...

关注 - 16

粉丝 - 297

+加关注

5

« 上一篇:SpringMVC学习系列(5)
之 数据绑定-2

» 下一篇:SpringMVC学习系列(7)
之 格式化显示

posted @ 2014-05-23 00:09 Miss When... 阅读(17477) 评论(20) 编辑 收藏

评论列表

#1楼 2014-05-23
09:48 梦云工作室

感谢LZ
支持(0)反对(0)

#2楼[楼主] 2014-05-23
16:07 Miss When...

@梦云工作室

不客气~~~
支持(0)反对(0)

#3楼 2014-05-23
17:01 地球上的火星人

刚好公司开始从struts2转向springmvc,跟着学习了。。
支持(0)反对(0)

#4楼[楼主] 2014-05-23
17:17 Miss When...

@地球上的火星人

越来越多的人选择Spring MVC了吗?看来当初选择Spring MVC是正确的,哇哈哈~~~
支持(0)反对(0)

#5楼 2014-10-30
14:03 口我

找了半天,终于找到篇靠谱的文章,多谢博主,继续加油啊
支持(0)反对(0)

#6楼 2014-11-24
17:04 极品Se狼

您好,我在做SpringMVC学习系列(6) 之 数据验证的练习,当导入validation-api-1.0.0.GA.jar时程序出现500错误,不知道如何解决。。
支持(0)反对(0)

#7楼 2015-02-22
17:26 淼淼淼

LZ这种数据验证和用js验证的有什么区别?这种有什么优势?
支持(0)反对(0)

#8楼[楼主] 2015-02-28
10:19 Miss When...

@极品Se狼

你看一下,eclipse中输出的具体错误信息是什么,因为我看不到错误信息,所以也不知道是哪里的问题。
支持(0)反对(0)

#9楼[楼主] 2015-02-28
10:22 Miss When...

@淼淼淼

js是前端验证对用户体验会更友好,但是如果不是用js提交的话,那么别人把浏览器的js关闭验证就失效了,通常会在前端和同台同时做验证,这样即使浏览器的js被关掉,用户提交的内容到服务器后还会做验证,更加安全。
支持(2)反对(0)

#10楼 2015-03-03
23:15 Gin.p

@Miss When...

LZ你好,之前看过一下这篇文章觉得不是太难,但是今天用起来的时候,每次提交空表单都出现404。我都是按照你一样的做了,

















后台不报错,表单有个字段没填提交就404,填好了的话还能进。LZ能帮我看看哪里问题吗?
支持(0)反对(0)

#11楼 2015-03-05
14:54 Gin.p

找到哪里错了,就是不知道原因,lz试一下将你的这个方法的参数,Model model,@Valid @ModelAttribute("contentModel") ValidateModel validateModel位置换一下看看会不会报404,加一个HttpServletRequest也会报错,换成这样子:

很奇怪的是,好像你那个项目的的参数顺序,就不会报错

支持(0)反对(0)

#12楼[楼主] 2015-03-06
09:53 Miss When...

@淼淼淼

不好意思,我机器上的开发环境没有了,所以没办法测试。不过这个问题应该是因为BindingResult必须跟随在自定义的模型之后,而你那里把Model放在两者之间了,你可以试一下:

public String test(@Valid @ModelAttribute("contentModel") ValidateModel validateModel, BindingResult result,Model model) throws NoSuchAlgorithmException

看还会返回404吗?
支持(0)反对(0)

#13楼 2015-03-06
12:37 Gin.p

@Miss When...

嗯,楼主所说是对的。只是这个规定有些意义不明。
支持(0)反对(0)

#14楼 2015-04-03
17:42 renwujie

楼主 问一下 为什么我的验证消息显示英文 不显示中文啊
支持(0)反对(0)

#15楼[楼主] 2015-04-07
13:03 Miss When...

@renwujie

请检查一下对应的中文资源文件添加了吗?对应的请求方式正确吗?
支持(0)反对(0)

#16楼 2015-05-04
17:57 王翊

@RequestMapping(value="/test", method = {RequestMethod.GET})

public String test(Model model){

if(!model.containsAttribute("contentModel")){

model.addAttribute("contentModel", new ValidateModel());

}

return "validatetest";

}

咨询楼主:不知道if判断里面有什么用,这是get提交,好像不会记录状态,那么model.containsAttribute("contentModel")的状态也就不会被记录下来,每次都要model.addAttribute("contentModel", new ValidateModel());而这句话的实际意义是什么呢?组件form时有用还是别的?
支持(0)反对(0)

#17楼 2015-06-18
13:50 野良猫

楼主,请问为什么我最后显示的是{email.not.correct}而不是"电子邮件不能为空"?
支持(0)反对(0)

#18楼 2015-07-13
14:29 骑着乌龟漫步

楼主,我照着你的代码写的,却报了很多错,有一个貌似是说没找到validationMessageSource这个属性,你给看看我这是怎么回事儿?






支持(0)反对(0)

#19楼[楼主] 2015-07-14
09:16 Miss When...

@骑着乌龟漫步

你项目resource文件夹下面有validatemessages.properties这个文件吗?
支持(0)反对(0)

#20楼 2015-07-14
09:38 骑着乌龟漫步

@Miss When...

好了,是我应用的jar包的问题,我把你的jar包导入之后就没有问题了,谢谢lz
支持(0)反对(0)

刷新评论刷新页面返回顶部

注册用户登录后才能发表评论,请 登录 或 注册,访问网站首页。

【推荐】50万行VC++源码: 大型组态工控、电力仿真CAD与GIS源码库

【推荐】融云即时通讯云-专注为 App 开发者提供IM云服务

【推荐】极光推送-20多万开发者都在用的推送服务平台,免费接入体验

【专享】阿里云9折优惠码:bky758





最新IT新闻:

· iOS端Chrome浏览器升级:支持分屏优化网购体验

· 研究显示语音助手同样会分散驾驶员注意力

· 研究人员在人体内首次检测出碳纳米管

· 苹果新专利:手机跌落时 屏幕能自动伸出保护片

· 领导力的核心秘诀:将问题紧紧握在自己手里!

» 更多新闻...





最新知识库文章:

· 什么时候应该避免写代码注释?

· 持续集成是什么?

· 人,技术与流程

· HTTPS背后的加密算法

· 下一代云计算模式:Docker正掀起个性化商业革命

» 更多知识库文章...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: