参考:http://www.cnblogs.com/liukemng/category/578644.html

先进行配置:

<!-- 默认的注解映射的支持 -->
<mvc:annotation-driven validator="validator" conversion-service="conversion-service" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean> <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>

model:

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

validatetest.jsp:(用于提交数据的表单页面)

<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>

validatesuccess.jsp:(验证通过后,跳转的页面)

<body>
验证成功!
</body>

from表单请求式:

controller:

/**
* 请求该地址,进入表单页
* @param model
* @return
*/
@RequestMapping(value="/test", method = {RequestMethod.GET})
public String test(Model model){
if(!model.containsAttribute("contentModel")){
model.addAttribute("contentModel", new ValidateModel());
}
return "validatetest";
}
/**
* 请求该地址,校验数据
* @param model
* @param validateModel
* @param result
* @return
*/
@RequestMapping(value="/test", method = {RequestMethod.POST},produces = "text/html")
public String test2(Model model,@Valid @ModelAttribute("contentModel") ValidateModel validateModel,BindingResult result) {
//如果有验证错误 返回到form页面
if(result.hasErrors()) {
test(model);
}
return "validatesuccess";
}

bindingresult里有校验的结果,model里会携带bindingresult,然后在jsp页面渲染 错误信息!

结果示例:

AJAX请求式:

/**
* ajax 验证数据
* @param validateModel
* @param result
* @return
*/
@RequestMapping(value="/test", method = {RequestMethod.POST},produces = "text/html;charset=UTF-8")
@ResponseBody
public String test(@Valid ValidateModel validateModel, BeanPropertyBindingResult result) {
if(result.hasErrors()) {
StringBuilder sb = new StringBuilder();
List<ObjectError> lit = result.getAllErrors();
for (ObjectError objectError : lit) {
FieldError error = (FieldError)objectError;
String a = error.getDefaultMessage();
sb.append(a);
}
return sb.toString();
}
return "success";
}
        $("#test").click(function () {
$.ajax({
url:"test",
type:"post",
data:"name=&age=&email=1",
success:function (result) {
alert(result);
}
});
});

这个controller,重点是,我将bindingresult 替换城了 BeanPropertyBindingResult 对象了,因为从这个对象里,能将错误的信息获取出来。

然后将错误的信息拼接返回。结果:

下面是主要的验证注解及说明:

注解

适用的数据类型

说明

@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,CollectionMap 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格式

最新文章

  1. UDP(强行关闭了一个现有的连接远程主机)
  2. AgileEAS.NET SOA 中间件平台.Net Socket通信框架-简单例子-实现简单的服务端客户端消息应答
  3. .net frameworkAPI文档下载地址
  4. Debian7安装GCC4.8
  5. CoreText实现图文混排之点击事件
  6. Css 描点
  7. 超大批量删除redis中无用key+配置
  8. uva 10306 - e-Coins(完全背包)
  9. PHP和js实时倒计时
  10. Assembly Experiment3
  11. Python 通过 SMTP 发送邮件
  12. Linux ubantu中安装虚拟/使用环境virtualenv以及python flask框架
  13. go标准库的学习-database/sql/driver
  14. SharePoint online Multilingual support - Development(2)
  15. JS构造函数内的方法与构造函数prototype属性上方法的对比
  16. 【docker】 centos7 下 使用docker 安装 LNMP
  17. CUDA C Programming Guide 在线教程学习笔记 Part 2
  18. oracel become INDEX UNUSABLE
  19. Maven install 报错: Failed to execute goalorg.apache.maven.plugins:maven-gpg-plugin:1.4:sign (sign-art
  20. kubernetes 阿里云安装(kubeadm方式)

热门文章

  1. Linux 简单socket实现TCP通信
  2. Android Service 服务(二)—— BroadcastReceiver
  3. Spring框架(依赖注入)
  4. 论 Web 前端加密的意义
  5. 开发一个delphi写的桌面图标管理代码
  6. C#判断字符串是否为数字字符串
  7. BZOJ4321 queue2(动态规划)
  8. Eclipse中的引用项目报Could not find *.apk!解决办法
  9. Codeforces Round #535 (Div. 3) 题解
  10. JavaScript 被忽视的细节