- 浏览: 921705 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (251)
- WebService (17)
- IBatis (22)
- Hibernate (1)
- SpringMVC - 基础篇 (32)
- Spring (15)
- Java (11)
- JVM及调优 - 基础篇 (4)
- 集群 (14)
- 数据库 (17)
- WebSphere (5)
- 多线程 (4)
- 集合、容器 (2)
- DB Pool (1)
- Power Designer (5)
- Maven基础 (5)
- JS (14)
- WEB 前端 (5)
- 实用小工具 (17)
- 社会、人 (2)
- 乱七八糟 (18)
- ASM&CGLIB - 基础篇 (12)
- 缓存 (1)
- 性能 (1)
- 设计之殇 (1)
- 分布式事务 (1)
- 单点登录 (11)
- 分布式 Session (4)
- Memcached - 基础篇 (6)
最新评论
-
一笑_奈何:
楼主写的还真行不错。
扫盲贴 - J2EE集群之JNDI集群实现 -
xuezhongyu01:
博主写的很详细,但最后还是没明白,最后调用BasicDataS ...
Spring中的destroy-method方法 -
Mr梁:
commons-fileupload.jar commons- ...
SpringMVC 中文件上传 MultipartResolver -
Eywa:
总结的很不错
ORACLE CASE WHEN 及 SELECT CASE WHEN的用法 -
TryRelax:
fastjson 比 jackson 好用吧?
Spring MVC Jackson DateFormat
一、准备校验时使用的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; @Email 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中内容协商【统一资源多种展现json xml html】
2013-09-12 15:58 3371在我们实际的开发中,往往需要SpringMVC ... -
Spring为某个属性注入值或为某个方法的返回值
2013-08-26 16:02 1431项目中用到需要初始化一些数据,Spring提供了filed的 ... -
SpringMVC 基础知识点小结
2013-08-23 15:26 2228参照:http://zachary-g ... -
使用SpringMVC Restful 开发思考
2013-03-18 14:23 1238一、rest思想 此部分 ... -
Spring MVC Jackson DateFormat
2012-10-14 15:59 2149使用Spring MVC 里的Jackson返回JSON时,遇 ... -
SpringMVC 中文件上传 MultipartResolver
2011-12-17 17:44 55039基于前面文章的基础上。 一、准备 需要的jar ... -
SpringMVC 异常处理初探
2011-12-12 12:18 8173Web应用中对于异常的处理方式与其他形式的应用并没有太大的不同 ... -
SringMVC 注解标记备忘录
2011-12-10 22:42 2083Spring MVC注解开发中常用标签,如下表: ... -
SpringMVC拦截器简单使用
2011-12-10 22:17 93523基于上一篇文章的基础上 一、拦截器的配置 1、 ... -
SpringMVC生成JSON(三)
2011-12-10 01:16 20595基于上一篇文章的代码基础上 一、准备工作 1、 下载依赖库 ... -
SpringMVC生成JSON(二)
2011-12-06 21:24 8233基于上一篇文章的代码基础上 开始Jackson之旅。 一、准 ... -
SpringMVC 生成JSON(一)
2011-12-04 19:37 3259本示例基于前面几篇文章的代码。 一、JSON-lib框 ... -
Spring MVC处理重定向的传参
2011-12-03 21:35 6517一、Spring MVC是如何处理重定向的传参? 现提供一种 ... -
Spring MVC3.0的RESTFul方式的访问
2011-12-03 20:59 1596上一篇以简单介绍了 ... -
SpringMVC之用注解控制器
2011-12-03 19:53 2462在传统的Spring MVC开发方法中,必须在Bean配置 ... -
SpringMVC例子代码小汇总
2011-11-20 11:18 1860一、结构 二、Jar版本及使用jar包 ... -
SpringMVC 拦截器实现分析
2011-11-20 00:10 5352一、Servlet Filter与Spring interce ... -
SpringMVC学习笔记(三) --- 映射处理器(续)
2011-10-07 21:46 1628<?xml version="1.0" ... -
SpringMVC学习笔记(二) --- 后端控制器之MultiActionController(一)
2011-10-07 21:07 2008创建处理多个请求的控制器 根据"每个请求一个 ... -
SpringMVC学习笔记(二) --- 后端控制器之CommandController、 FormController(三)
2011-10-07 16:09 2956另一种表单封装的参数的Controller是AbstractC ...
相关推荐
本篇文章主要介绍了SpringMVC 使用JSR-303进行校验 @Valid示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
一、准备校验时使用的JARvalidation-api-1.1.0.Final.jar:JDK的接口;hibernate-validator-5.2.4.Final.jar是对上述接口的实现;或者在Maven中添加依赖:1.<dependency> 2. <groupId>org.hibernate</groupId> 3. ...
本篇文章主要介绍了详解springmvc使用JSR-303进行数据校验,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
SpringMVC ---- HelloWorld ---- 代码 SpringMVC ---- HelloWorld ---- 代码 SpringMVC ---- HelloWorld ---- 代码 SpringMVC ---- HelloWorld ---- 代码 SpringMVC ---- HelloWorld ---- 代码 SpringMVC ---- Hello...
springmvc 使用hibernate-validator校验框架所需的校验包
redis-service_pubsub.rar。 springMVC集成spring-data-redis实现发布订阅。
SpringMVC-Mybatis-Shiro-redis-master..............
基于SpringMVC Mybatis Shiro Redis 的权限管理系统,该系统已经部署到线上,线上访问地址:http://shiro.itboy.net,登录账号:admin 密码:sojson,,详细教程参考sojson.com/shiro
基于SpringMVC、Mybatis、Redis、Freemarker的Shiro管理Demo源码的升级版 相关详细配置说明请参看 --> http://www.sojson.com/shiro
hibernate-validator-5.2.4.Final.jar hibernate-validator-annotation-processor-5.2.4.Final.jar hibernate-validator-cdi-5.2.4.Final.jar validation-api-1.1.0.Final.jar jboss-logging-3.2.1.Final.jar ...
项目中所需的jar包在压缩包中已提供,项目中用到了JSR303和hibernate-validator的技术,大量采用了注解@NotNull,@Email,@Length,@Max,@Pattern,@Size等,此外还采用了自定义注解,验证信息全部配置在属性文件中.
SpringMVC------从HelloWorld开始
SpringMVC JSR303数据校验DEMO(附:JSR303的JAR包) SpringMVC JSR303数据校验DEMO(附:JSR303的JAR包)
springmvc+国际化i18N+springmvc验证+jetbrick-template使用+@responsebody+谷歌guava: 1)围绕springmvc做的国际化 2)围绕springmvc做的验证 3)使用的jetbrick-template模板引擎 ……
用户Spring mvc Jackson自动转化的支持
springmvc-framework-官方中文版
springmvc-json-lib.rar springmvc-json-lib.rar
easyui的tree组件的使用,使用springmvc作为后台支持,前后通信是实现tree的操作
springMVC-Hibernate-Oracle进行开发,一个小的demo 大家可以使用
springmvc-without-webxml springmvc-without-webxmlspringmvc-without-webxml