[springMVC]SpringMVC 使用JSR-303进行校验 @Valid

原文地址:http://exceptioneye.iteye.com/blog/1305040


一、准备校验时使用的JAR

      

  说明:

         validation-api-1.0.0.GA.jar是JDK的接口;

         hibernate-validator-4.2.0.Final.jar是对上述接口的实现。

 

------------------------------------------------------------------------------------------------

新增一个测试的pojo bean ,增加jsr 303格式的验证annotation

Java代码  复制代码   收藏代码
Java代码   收藏代码
  1. @NotEmpty  
  2. private String userName;  
  3. @Email  
  4. private String email;  


在controller 类中的handler method中,对需要验证的对象前增加@Valid 标志

Java代码  复制代码   收藏代码
Java代码   收藏代码
  1. @RequestMapping("/valid")  
  2. public String valid(@ModelAttribute("vm") [color=red]@Valid[/color] ValidModel vm, BindingResult result) {  
  3.     if (result.hasErrors()) {  
  4.         return "validResult";  
  5.     }  
  6.   
  7.     return "helloworld";  
  8. }  


增加显示验证结果的jsp如下

Jsp代码  复制代码   收藏代码
Jsp代码   收藏代码
  1. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>  
  2.   
  3. <html>  
  4. <head>  
  5. <title>Reservation Form</title>  
  6. <style>  
  7. .error {  
  8.     color: #ff0000;  
  9.     font-weight: bold;  
  10. }  
  11. </style>  
  12. </head>  
  13.   
  14. <body>  
  15.     <form:form method="post" modelAttribute="vm">  
  16.         <form:errors path="*" cssClass="error" />  
  17.         <table>  
  18.             <tr>  
  19.                 <td>Name</td>  
  20.                 <td><form:input path="userName" />  
  21.                 </td>  
  22.                 <td><form:errors path="userName" cssClass="error" />  
  23.                 </td>  
  24.             </tr>  
  25.             <tr>  
  26.                 <td>email</td>  
  27.                 <td><form:input path="email" />  
  28.                 </td>  
  29.                 <td><form:errors path="email" cssClass="error" />  
  30.                 </td>  
  31.             </tr>  
  32.       
  33.             <tr>  
  34.                 <td colspan="3"><input type="submit" />  
  35.                 </td>  
  36.             </tr>  
  37.         </table>  
  38.     </form:form>  
  39. </body>  
  40. </html>  


访问 http://localhost:8080/springmvc/valid?userName=winzip&email=winzip 
查看验证结果。 
二:自定义jsr 303格式的annotation 
参考hibernate validator 4 reference 手册中3.1节,增加一个自定义要求输入内容为定长的annotation验证类 
新增annotation类定义

Java代码  复制代码   收藏代码
Java代码   收藏代码
  1. @Target( { METHOD, FIELD, ANNOTATION_TYPE })  
  2. @Retention(RUNTIME)  
  3. @Constraint(validatedBy = FixLengthImpl.class)  
  4. public @interface FixLength {  
  5.   
  6.     int length();  
  7.     String message() default "{net.zhepu.web.valid.fixlength.message}";  
  8.   
  9.     Class<?>[] groups() default {};  
  10.   
  11.     Class<? extends Payload>[] payload() default {};  
  12. }  


及具体的验证实现类如下

Java代码  复制代码   收藏代码
Java代码   收藏代码
  1. public class FixLengthImpl implements ConstraintValidator<FixLength, String> {  
  2.     private int length;  
  3.     @Override  
  4.     public boolean isValid(String validStr,  
  5.             ConstraintValidatorContext constraintContext) {  
  6.         if (validStr.length() != length) {  
  7.             return false;  
  8.         } else {  
  9.             return true;  
  10.         }  
  11.     }  
  12.   
  13.     @Override  
  14.     public void initialize(FixLength fixLen) {  
  15.         this.length = fixLen.length();  
  16.     }  
  17. }  


为使自定义验证标注的message正常显示,需要修改servlet context配置文件,新增messageSource bean,如下

Xml代码  复制代码   收藏代码
  1.   
Xml代码   收藏代码
  1. <bean id="messageSource"  
  2.     class="org.springframework.context.support.ReloadableResourceBundleMessageSource"  
  3.     p:fallbackToSystemLocale="true" p:useCodeAsDefaultMessage="false"  
  4.     p:defaultEncoding="UTF-8">  
  5.     <description>Base message source to handle internationalization  
  6.     </description>  
  7.     <property name="basenames">  
  8.         <list>  
  9.             <!-- main resources -->  
  10.             <value>classpath:valid/validation</value>  
  11.         </list>  
  12.     </property>  
  13. </bean>  


表示spring 将从路径valid/validation.properties中查找对于的message。 
新增valid bean 引用新增的messageSource bean,表示valid message将从messageSource bean 注入。

Xml代码  复制代码   收藏代码
Xml代码   收藏代码
  1. <bean id="validator"  
  2.     class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"  
  3.     p:validationMessageSource-ref="messageSource">  
  4.     <description>Enable the bean validation provider, and configure it to  
  5.         use the messageSource when resolving properties</description>  
  6. </bean>  



修改 <mvc:annotation-driven> 增加对validator bean的引用

Xml代码  复制代码   收藏代码
Xml代码   收藏代码
  1. <mvc:annotation-driven validator="validator" />  



最后修改之前新增的pojo bean ,新增一个mobileNO属性并增加对自定义标注的引用

Java代码  复制代码   收藏代码
Java代码   收藏代码
  1. @FixLength(length=11)  
  2. private String mobileNO;  


在前端jsp中也增加新字段的支持

Jsp代码  复制代码   收藏代码
Jsp代码   收藏代码
  1. <tr>  
  2.     <td>mobileno</td>  
  3.     <td><form:input path="mobileNO" />  
  4.     </td>  
  5.     <td><form:errors path="mobileNO" cssClass="error" />  
  6.     </td>  
  7. </tr>  



可访问url http://localhost:8080/springmvc/valid?userName=winzip&email=winzip&mobileNO=138188888 
来查看修改的结果。 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值