参考: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格式

springmvc JSR303 Validate 注解式,校验数据的更多相关文章

  1. 第5章—构建Spring Web应用程序—关于spring中的validate注解后台校验的解析

    关于spring中的validate注解后台校验的解析 在后台开发过程中,对参数的校验成为开发环境不可缺少的一个环节.比如参数不能为null,email那么必须符合email的格式,如果手动进行if判 ...

  2. SSM-SpringMVC-14:SpringMVC中大话注解式开发基础--呕心沥血版

     ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 注解的基础我不再多啰嗦,百度一搜很多,很详细啊,我就讲一下SpringMVC中的注解入门 通过注解的方式定义 ...

  3. SSM-SpringMVC-16:SpringMVC中小论注解式开发之访问方式篇

     ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 访问方式可以指定,打个比方,你通过get方式进入登陆页面,通过post发送ajax数据库校验或者post提交 ...

  4. SSM-SpringMVC-15:SpringMVC中小论注解式开发之通配符篇

     ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 此处改了下标题,小论,为什么不说大话了呢?哎,质量不够啊,通配符篇提取不出更多可以讲的滔滔不绝的套路 通配符 ...

  5. springmvc 开涛 注解式控制器

    版本 定义处理器类 处理器映射适配器 备注 支持的注解 2.5前 controller       2.5 注解 DefaultAnnotationHandlerMapping AnnotationM ...

  6. 使用@Validated校验数据(除数据库做辅助)

    一.controller层 /** * 使用@Validated来进行校验 * @author HuangJingNa * @date 2019年12月23日 下午6:02:20 * * @param ...

  7. spring(7)--注解式控制器的数据验证、类型转换及格式化

    7.1.简介 在编写可视化界面项目时,我们通常需要对数据进行类型转换.验证及格式化. 一.在Spring3之前,我们使用如下架构进行类型转换.验证及格式化: 流程: ①:类型转换:首先调用Proper ...

  8. SpringMVC的数据转换,格式化和数据校验

          在SpringMVC中,根据请求方法签名不同,将请求消息中的消息以一定的方式转换并绑定到请求方法的参数中,在请求信息到达真正调用处理方法的这一段时间内,SpringMVC还会完成很多其他的 ...

  9. SpringMVC使用@Valid注解进行数据验证

    SpringMVC使用@Valid注解进行数据验证   from:https://blog.csdn.net/zknxx/article/details/52426771 我们在做Form表单提交的时 ...

随机推荐

  1. gcc6.3编译c++11的程序链接opencv时字符型函数未定义

    在Windows下编写图像处理程序,由于要使用regex,升级了mingw,编译c++11代码.之前代码中使用了opencv2.4.10,一直运行良好,升级编译器以后发现了错误:undefined r ...

  2. 山科 STUST OJ Problem B: 编写函数:String to Double (II) (Append Code)

    这道题没啥别的毛病,我的错误在于看不懂题. 另外还有一点是注意浮点数存在-0 #include <stdio.h> #include <ctype.h> #include &l ...

  3. SDUST OJ Problem G 动态的字符串排序

    Description 把字符串按照ASCII码序的从小到大排列出来. 串的ASCII码序遵循如下递归定义: 1 两串的前n-1个字符相同,第n个字符ASCII码序小的排在前面:2 只有两串的字符完全 ...

  4. Android—实现科大讯飞语音合成

    背景(可以不看) 实验室项目开发的APP需要有语音提示功能,之前的做法是人工录音,剪辑片段,调用Android的多媒体,播放,呵呵呵,,,这是21世纪!这样肯定显得有点low啊,且不说档次,应用场景也 ...

  5. iOS-调用百度地图,苹果自带地图,高德地图,谷歌地图导航方法

    - (void)actionSheet : (ServiceNetworkModel *)model{ __block NSString *urlScheme = @"demoURI://& ...

  6. 从零开始配置Jenkins(一)——基本配置

    [背景] 由于项目变动,需要重新搭建jenkins环境,并在新搭建的平台下进行配置.之前,小编只是照猫画虎的用jenkins手动构建,虽然也维护过一段时间,但对于其中的原理并不是很了解.这下可好了,学 ...

  7. StrutsResultSupport的使用

    在有特殊情况时:如果没有异常信息,但是有错误并且有错误信息等内容:此时也需要进行友好的错误处理的话,那么可以借助StrutsResultSupport 返回结果类型来实现特定处理.此种方式先需要继承S ...

  8. ELK6.2.4集群

    ELK6.2.4集群安装使用 https://www.cnblogs.com/frankdeng/p/9139035.html 一 简介 Elasticsearch是一个高度可扩展的开源全文搜索和分析 ...

  9. 周记【距gdoi:126天】

    这周比上周好了那么一点点……但还是有点呵呵 搞了仙人掌图(当然不是动态的……),以及一个远古算法2-sat(神奇的对称性运用,需要巨大脑洞的建边). 然后关于高考不加分竞赛被“打压”……大神们都发表了 ...

  10. 洛谷 [CQOI2015]选数 解题报告

    [CQOI2015]选数 题目描述 我们知道,从区间\([L,H]\)(\(L\)和\(H\)为整数)中选取\(N\)个整数,总共有\((H-L+1)^N\)种方案. 小\(z\)很好奇这样选出的数的 ...