SpringMVC 使用JSR-303进行校验 @Valid
注意:1 public String save(@ModelAttribute("house") @Valid House entity, BindingResult result,HttpServletRequest request, Model model) BindingResult 必须放在model,request前面
2 validation-api-1.0.0.GA.jar是JDK的接口;hibernate-validator-4.2.0.Final.jar是对上述接口的实现。hibernate-validator-4.2.0.Final可以,但是hibernate-validator-4.3.0.Final报错
|
验证注解 |
验证的数据类型 |
说明 |
|
@AssertFalse |
Boolean,boolean |
验证注解的元素值是false |
|
@AssertTrue |
Boolean,boolean |
验证注解的元素值是true |
|
@NotNull |
任意类型 |
验证注解的元素值不是null |
|
@Null |
任意类型 |
验证注解的元素值是null |
|
@Min(value=值) |
BigDecimal,BigInteger, byte, short, int, long,等任何Number或CharSequence(存储的是数字)子类型 |
验证注解的元素值大于等于@Min指定的value值 |
|
@Max(value=值) |
和@Min要求一样 |
验证注解的元素值小于等于@Max指定的value值 |
|
@DecimalMin(value=值) |
和@Min要求一样 |
验证注解的元素值大于等于@ DecimalMin指定的value值 |
|
@DecimalMax(value=值) |
和@Min要求一样 |
验证注解的元素值小于等于@ DecimalMax指定的value值 |
|
@Digits(integer=整数位数, fraction=小数位数) |
和@Min要求一样 |
验证注解的元素值的整数位数和小数位数上限 |
|
@Size(min=下限, max=上限) |
字符串、Collection、Map、数组等 |
验证注解的元素值的在min和max(包含)指定区间之内,如字符长度、集合大小 |
|
@Past |
java.util.Date, java.util.Calendar; Joda Time类库的日期类型 |
验证注解的元素值(日期类型)比当前时间早 |
|
@Future |
与@Past要求一样 |
验证注解的元素值(日期类型)比当前时间晚 |
|
@NotBlank |
CharSequence子类型 |
验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的首位空格 |
|
@Length(min=下限, max=上限) |
CharSequence子类型 |
验证注解的元素值长度在min和max区间内 |
|
@NotEmpty |
CharSequence子类型、Collection、Map、数组 |
验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0) |
|
@Range(min=最小值, max=最大值) |
BigDecimal,BigInteger,CharSequence, byte, short, int, long等原子类型和包装类型 |
验证注解的元素值在最小值和最大值之间 |
|
@Email(regexp=正则表达式, flag=标志的模式) |
CharSequence子类型(如String) |
验证注解的元素值是Email,也可以通过regexp和flag指定自定义的email格式 |
|
@Pattern(regexp=正则表达式, flag=标志的模式) |
String,任何CharSequence的子类型 |
验证注解的元素值与指定的正则表达式匹配 |
|
@Valid |
任何非原子类型 |
指定递归验证关联的对象; 如用户对象中有个地址对象属性,如果想在验证用户对象时一起验证地址对象的话,在地址对象上加@Valid注解即可级联验证 |
一、准备校验时使用的JAR

说明:
validation-api-1.0.0.GA.jar是JDK的接口;
hibernate-validator-4.2.0.Final.jar是对上述接口的实现。
------------------------------------------------------------------------------------------------
新增一个测试的pojo bean ,增加jsr 303格式的验证annotation
- @NotEmpty
- private String userName;
- private String email;
在controller 类中的handler method中,对需要验证的对象前增加@Valid 标志
- @RequestMapping("/valid")
- public String valid(@ModelAttribute("vm") [color=red]@Valid[/color] ValidModel vm, BindingResult result) {
- if (result.hasErrors()) {
- return "validResult";
- }
- return "helloworld";
- }
增加显示验证结果的jsp如下
- <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
- <html>
- <head>
- <title>Reservation Form</title>
- <style>
- .error {
- color: #ff0000;
- font-weight: bold;
- }
- </style>
- </head>
- <body>
- <form:form method="post" modelAttribute="vm">
- <form:errors path="*" cssClass="error" />
- <table>
- <tr>
- <td>Name</td>
- <td><form:input path="userName" />
- </td>
- <td><form:errors path="userName" cssClass="error" />
- </td>
- </tr>
- <tr>
- <td>email</td>
- <td><form:input path="email" />
- </td>
- <td><form:errors path="email" cssClass="error" />
- </td>
- </tr>
- <tr>
- <td colspan="3"><input type="submit" />
- </td>
- </tr>
- </table>
- </form:form>
- </body>
- </html>
访问 http://localhost:8080/springmvc/valid?userName=winzip&email=winzip
查看验证结果。
二:自定义jsr 303格式的annotation
参考hibernate validator 4 reference 手册中3.1节,增加一个自定义要求输入内容为定长的annotation验证类
新增annotation类定义
- @Target( { METHOD, FIELD, ANNOTATION_TYPE })
- @Retention(RUNTIME)
- @Constraint(validatedBy = FixLengthImpl.class)
- public @interface FixLength {
- int length();
- String message() default "{net.zhepu.web.valid.fixlength.message}";
- Class<?>[] groups() default {};
- Class<? extends Payload>[] payload() default {};
- }
及具体的验证实现类如下
- public class FixLengthImpl implements ConstraintValidator<FixLength, String> {
- private int length;
- @Override
- public boolean isValid(String validStr,
- ConstraintValidatorContext constraintContext) {
- if (validStr.length() != length) {
- return false;
- } else {
- return true;
- }
- }
- @Override
- public void initialize(FixLength fixLen) {
- this.length = fixLen.length();
- }
- }
为使自定义验证标注的message正常显示,需要修改servlet context配置文件,新增messageSource bean,如下
- <bean id="messageSource"
- class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
- p:fallbackToSystemLocale="true" p:useCodeAsDefaultMessage="false"
- p:defaultEncoding="UTF-8">
- <description>Base message source to handle internationalization
- </description>
- <property name="basenames">
- <list>
- <!-- main resources -->
- <value>classpath:valid/validation</value>
- </list>
- </property>
- </bean>
表示spring 将从路径valid/validation.properties中查找对于的message。
新增valid bean 引用新增的messageSource bean,表示valid message将从messageSource bean 注入。
- <bean id="validator"
- class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"
- p:validationMessageSource-ref="messageSource">
- <description>Enable the bean validation provider, and configure it to
- use the messageSource when resolving properties</description>
- </bean>
修改 <mvc:annotation-driven> 增加对validator bean的引用
- <mvc:annotation-driven validator="validator" />
最后修改之前新增的pojo bean ,新增一个mobileNO属性并增加对自定义标注的引用
- @FixLength(length=11)
- private String mobileNO;
在前端jsp中也增加新字段的支持
- <tr>
- <td>mobileno</td>
- <td><form:input path="mobileNO" />
- </td>
- <td><form:errors path="mobileNO" cssClass="error" />
- </td>
- </tr>
可访问url http://localhost:8080/springmvc/valid?userName=winzip&email=winzip&mobileNO=138188888
来查看修改的结果。
三 json输入的验证
Spring mvc 3.0.5中对于json格式的输入直接使用@valid标注有问题,目前这个bug还未修复 (见 SPR-6709),预计在3.1 m2版本中会修复。
在此之前,可以通过如下几种方式来对json(或xml)格式的输入来进行验证。
1:在handler method中直接对输入结果进行验证
- @RequestMapping("/validJson1")
- @ResponseBody
- public JsonResult processSubmitjson(@RequestBody ValidModel vm,
- HttpServletRequest request) {
- JsonResult jsonRst = new JsonResult();
- Set<ConstraintViolation<ValidModel>> set = validator.validate(vm);
- for (ConstraintViolation<ValidModel> violation : set) {
- String propertyPath = violation.getPropertyPath().toString();
- ;
- String message = violation.getMessage();
- log.error("invalid value for: '" + propertyPath + "': "
- + message);
- }
- if (!set.isEmpty()){
- jsonRst.setSuccess(false);
- jsonRst.setMsg("输入有误!");
- return jsonRst;
- }
- jsonRst.setSuccess(true);
- jsonRst.setMsg("输入成功!");
- return jsonRst;
- }
可通过修改后的helloworld.jsp中的json valid test1按钮进行调用测试。
2:将此验证逻辑封装为一个AOP,当需验证的对象前有@valid标注和@RequestBody标注时开始验证
新增handler method如下
- @RequestMapping("/validJson2")
- @ResponseBody
- public JsonResult testJson4(@RequestBody @Valid ValidModel vm){
- log.info("handle json for valid");
- return new JsonResult(true,"return ok");
- }
这里没有对输入值做任何验证,所有的验证都在AOP中完成。
修改pom.xml增加对AOP相关类库的引用。
- <dependency>
- <groupId>org.aspectj</groupId>
- <artifactId>aspectjweaver</artifactId>
- <version>1.6.11</version>
- </dependency>
- <dependency>
- <groupId>cglib</groupId>
- <artifactId>cglib</artifactId>
- <version>2.2.2</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aop</artifactId>
- <version>${org.springframework.version}</version>
- </dependency>
修改servet context xml,增加对aop的支持。
- <!-- enable Spring AOP support -->
- <aop:aspectj-autoproxy proxy-target-class="true" />
最后,新增AOP类
- public class CustomerValidatorAOP {
- private Validator validator;
- @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
- private void controllerInvocation() {
- }
- @Around("controllerInvocation()")
- public Object aroundController(ProceedingJoinPoint joinPoint) throws Throwable {
- MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
- Method method = methodSignature.getMethod();
- Annotation[] annotationList = method.getAnnotations();
- /* for(Annotation anno:annotationList){
- System.out.println(ResponseBody.class.isInstance(anno));
- }
- */
- Annotation[][] argAnnotations = method.getParameterAnnotations();
- String[] argNames = methodSignature.getParameterNames();
- Object[] args = joinPoint.getArgs();
- for (int i = 0; i < args.length; i++) {
- if (hasRequestBodyAndValidAnnotations(argAnnotations[i])) {
- Object ret = validateArg(args[i], argNames[i]);
- if(ret != null){
- return ret;
- }
- }
- }
- return joinPoint.proceed(args);
- }
- private boolean hasRequestBodyAndValidAnnotations(Annotation[] annotations) {
- if (annotations.length < 2)
- return false;
- boolean hasValid = false;
- boolean hasRequestBody = false;
- for (Annotation annotation : annotations) {
- if (Valid.class.isInstance(annotation))
- hasValid = true;
- else if (RequestBody.class.isInstance(annotation))
- hasRequestBody = true;
- if (hasValid && hasRequestBody)
- return true;
- }
- return false;
- }
- private JsonResult validateArg(Object arg, String argName) {
- BindingResult result = getBindingResult(arg, argName);
- validator.validate(arg, result);
- if (result.hasErrors()) {
- JsonResult jsonresult = new JsonResult();
- jsonresult.setSuccess(false);
- jsonresult.setMsg("fail");
- return jsonresult;
- }
- return null;
- }
- private BindingResult getBindingResult(Object target, String targetName) {
- return new BeanPropertyBindingResult(target, targetName);
- }
- @Required
- public void setValidator(Validator validator) {
- this.validator = validator;
- }
这里只考虑了输入为json格式的情况,仅仅作为一种思路供参考,实际使用时需要根据项目具体情况进行调整。
可通过修改后的helloworld.jsp中的json valid test2按钮进行调用测试。
原文:http://starscream.iteye.com/blog/1068905
SpringMVC 使用JSR-303进行校验 @Valid的更多相关文章
- SpringMVC中的 JSR 303 数据校验框架说明
JSR 303 是java为Bean数据合法性校验提供的标准框架,它已经包含在JavaEE 6.0中. JSR 303 通过在Bean属性上标注类似于@NotNull.@Max等标准的注解指定校验规则 ...
- JSR 303 进行后台数据校验
一.JSR 303 1.什么是 JSR 303? JSR 是 Java Specification Requests 的缩写,即 Java 规范提案. 存在各种各样的 JSR,简单的理解为 JSR 是 ...
- SpringMVC中实现Bean Validation(JSR 303 JSR 349 JSR 380)
JSR 303是针对bean数据校验提出的一个规范.使用注解方式实现数据校验. 每个注解的用法这里就不多介绍,请移步JSR 303 - Bean Validation 介绍及最佳实践 笔者上面提到的J ...
- Springboot 使用 JSR 303 对 Controller 控制层校验及 Service 服务层 AOP 校验,使用消息资源文件对消息国际化
导包和配置 导入 JSR 303 的包.hibernate valid 的包 <dependency> <groupId>org.hibernate.validator< ...
- SpringMVC 数据转换 & 数据格式化 & 数据校验
数据绑定流程 1. Spring MVC 主框架将 ServletRequest 对象及目标方法的入参实例传递给 WebDataBinderFactory 实例,以创建 DataBinder 实例对象 ...
- SpringMVC——数据转换 & 数据格式化 & 数据校验
一.数据绑定流程 1. Spring MVC 主框架将 ServletRequest 对象及目标方 法的入参实例传递给 WebDataBinderFactory 实例,以创 建 DataBinder ...
- JSR 303 - Bean Validation 介绍及最佳实践
JSR 303 - Bean Validation 介绍及最佳实践 JSR 303 – Bean Validation 是一个数据验证的规范,2009 年 11 月确定最终方案.2009 年 12 月 ...
- JSR教程1——JSR 303 - Bean Validation介绍
1.Bean Validation 在任何时候,当你要处理一个应用程序的业务逻辑,数据校验是你必须要考虑和面对的事情.应用程序必须通过某种手段来确保输入进来的数据从语义上来讲是正确的.在通常的情况下, ...
- JSR 303 - Bean Validation 介绍及最佳实践(转)
JSR 303 – Bean Validation 是一个数据验证的规范,2009 年 11 月确定最终方案.2009 年 12 月 Java EE 6 发布,Bean Validation 作为一个 ...
随机推荐
- 深度学习论文翻译解析(三):Detecting Text in Natural Image with Connectionist Text Proposal Network
论文标题:Detecting Text in Natural Image with Connectionist Text Proposal Network 论文作者:Zhi Tian , Weilin ...
- Jenkins持续集成学习-Windows环境进行.Net开发1
目录 Jenkins持续集成学习-Windows环境进行.Net开发 目录 前言 目标 使用Jenkins 安装 添加.net环境配置 部署 结语 参考文档 Jenkins持续集成学习-Windows ...
- 多继承之MRO
一,python2和python3的区别 在python2中存在两种类:一个叫经典类,在python2.2之前,一直用的是经典类,经典类如果在基类的根什么都不写,那么它就是根:还有一个叫新式类,在py ...
- 【手记】解决excel无法设置单元格颜色且界面怪异+桌面图标文字老有色块等问题
注:问题是在XP上遇到的,不知道是否适用其它系统 问题现象 excel 2010成这样了: 关键是设置不了单元格颜色,无论是文字颜色还是背景色都设置不了,设了没变化.同时会发现桌面图标的文字总有底色: ...
- MVC架构介绍-序列化属性
实例产品基于asp.net mvc 5.0框架,源码下载地址:http://www.jinhusns.com/Products/Download 在设计时,如果能够预测到一些实体可能在后续的研发(或二 ...
- [Python] Python基础字符串
Python的语法采用缩进的方式,一般使用四个空格,并且是大小写敏感的 字符编码 计算机只能处理数字,如果要处理文本,必须先把文本转换成数字才能处理 采用8个比特(bit)作为一个字节(byte) 一 ...
- 搜藏一个php文件上传类
<?php /** * 上传文件类 * @param _path : 服务器文件存放路径 * @param _allowType : 允许上传的文件类型和所对应的MIME * @param _f ...
- 乐字节-Java8新特性之Base64和重复注解与类型注解
上一篇小乐给大家说了<乐字节-Java8新特性之Date API>,接下来小乐继续给大家说一说Java8新特性之Base64和重复注解与类型注解. 一.Base64 在Java 8中,内置 ...
- 【Java并发编程】18、PriorityBlockingQueue源码分析
PriorityBlockingQueue是一个基于数组实现的线程安全的无界队列,原理和内部结构跟PriorityQueue基本一样,只是多了个线程安全.javadoc里面提到一句,1:理论上是无界的 ...
- Cylinder Candy(积分+体积+表面积+旋转体)
Cylinder Candy Time Limit: 2 Seconds Memory Limit: 65536 KB Special Judge Edward the confectioner is ...