`

MVC 表单验证

 
阅读更多

表单:

 

用户注册页面: 名称:user.jsp
注册用户包含三项信息: 用户名,密码,邮箱。

[html]  view plain copy
  1. < %@ page  language = "java"   contentType = "text/html; charset=UTF-8" % >   
  2. < %@ taglib  prefix = "sf"   uri = "http://www.springframework.org/tags/form" % >   
  3.   
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">   
  5. < html >   
  6. < head >   
  7. < meta   http-equiv = "Content-Type"   content = "text/html; charset=UTF-8" >   
  8. < title > User Register Page </ title >   
  9. < style   type = "text/css" >   
  10. .error{  
  11.     color: red;   
  12. }  
  13. </ style >   
  14. </ head >   
  15.   
  16. < body >   
  17.     < %--  
  18.         这里指定页面绑定的对象 modelAttribute. 之前很困惑,  
  19.         为什么< form > 上最重要的  < form   action = "someAction.do" > 属性没了呢?   
  20.         后来发现,其实在controller中的方法以及指定了地址到method的对应关系,  
  21.         < form > 里的action属性就可以退休了。  
  22.     --%>   
  23.     < sf:form   method = "post"   modelAttribute = "user" >   
  24.         < p > 用户注册页面: </ p >   
  25.         < table   width = "60%"   align = "center" >   
  26.             < colgroup >   
  27.                 < col   width = "10%"   align = "right"   />   
  28.                 < col   />   
  29.             </ colgroup >      
  30.             < tr >   
  31.                 < th > 用户名: </ th >   
  32.                 < td >   
  33.                     < sf:input   path = "userName"   />   
  34.                     < small > length of userName is not more than 20. </ small > < br   />   
  35.                     < %-- 显示关于userName属性相关的错误信息。 --% >   
  36.                     < sf:errors   path = "userName"   cssClass = "error" />   
  37.                 </ td >   
  38.             </ tr >   
  39.             < tr >   
  40.                 < th > 密码: </ th >   
  41.                 < td >   
  42.                     < sf:password   path = "password"   />   
  43.                     < small > length of password is not less than 6. </ small > < br   />   
  44.                     < sf:errors   path = "password"   cssClass = "error"   />   
  45.                 </ td >   
  46.             </ tr >   
  47.             < tr >   
  48.                 < th > 邮箱: </ th >   
  49.                 < td >   
  50.                     < sf:input   path = "email" />   
  51.                     < small > format should confirm to general standard. </ small > < br   />   
  52.                     < sf:errors   path = "email"   cssClass = "error"   />   
  53.                 </ td >   
  54.             </ tr >            
  55.             < tr >   
  56.                 < td   colspan = "2"   align = "center" >   
  57.                     < input   type = "submit"   value = "注册"   />   
  58.                 </ td >   
  59.             </ tr >   
  60.         </ table >   
  61.     </ sf:form >   
  62. </ body >   
  63. </ html >   

 

校验方式一: JSR303 Bean Validation

在Spring3.1中增加的了对JSR303 Bean Validation规范的支持,不仅可以对Spring的 MVC进行校验,而且也可以对Hibernate的存储对象进行校验。是一个通用的校验框架。

 


环境准备:

A) 导入Hibernate-Validator  
要使用JSR303 校验框架, 需要加入框架的具体实现Hibernate-Validator, 在soureforge上下载最新的Hibernate-Validator , 当前版本为4.2.0 Final版。
在/WEB-INF/lib中导入 hibernate-validator-4.2.0.Final.jar, hibernate-validator-annotation-processor-4.2.0.Final.jar, 导入它的lib/required目录下内容slf4j-api-1.6.1.jar, validation-api-1.0.0.GA.jar;

B) 配置Spring对JSR 303 的支持。 
在你的 <servletName>-servlet.xml配置文件中,使用标签:

[html]  view plain copy
  1. < mvc:annotation-driven   />   

配置对JSR303的支持,包括制动查找Hibernate-Validator的实现等工作。


1) 可用的 JSR303注解

 

空检查

@Null       验证对象是否为null

@NotNull    验证对象是否不为null, 无法查检长度为0的字符串

@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.

@NotEmpty 检查约束元素是否为NULL或者是EMPTY.

 

Booelan检查

@AssertTrue     验证 Boolean 对象是否为 true  

@AssertFalse    验证 Boolean 对象是否为 false  

 

长度检查

@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内  

@Length(min=, max=) Validates that the annotated string is between min and max included.

 

日期检查

@Past           验证 Date 和 Calendar 对象是否在当前时间之前  

@Future     验证 Date 和 Calendar 对象是否在当前时间之后  

@Pattern    验证 String 对象是否符合正则表达式的规则

 

数值检查,建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为"",Integer为null

@Min            验证 Number 和 String 对象是否大等于指定的值  

@Max            验证 Number 和 String 对象是否小等于指定的值  

@DecimalMax 被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度

@DecimalMin 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度

@Digits     验证 Number 和 String 的构成是否合法  

@Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。

 

@Range(min=, max=) Checks whether the annotated value lies between (inclusive) the specified minimum and maximum.

@Range(min=10000,max=50000,message="range.bean.wage")
private BigDecimal wage;

 

@Valid 递归的对关联对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证)

@CreditCardNumber信用卡验证

@Email 验证是否是邮件地址,如果为null,不进行验证,算通过验证。

@ScriptAssert(lang= ,script=, alias=)

@URL(protocol=,host=, port=,regexp=, flags=)

 

 

 

 


通过上述Constraint约束后的User对象如下:

[java]  view plain copy
  1. package  org.study.domain;  
  2.   
  3. import  javax.validation.constraints.Pattern;  
  4. import  javax.validation.constraints.Size;  
  5.   
  6. import  org.study.validation.annotation.NotEmpty;  
  7.   
  8. public   class  User {  
  9.       
  10.     @Size  (min= 3 , max= 20 , message= "用户名长度只能在3-20之间" )  
  11.     private  String userName;  
  12.       
  13.     @Size  (min= 6 , max= 20 , message= "密码长度只能在6-20之间" )  
  14.     private  String password;  
  15.       
  16.     @Pattern  (regexp= "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" , message= "邮件格式错误" )  
  17.     private  String email;  
  18.       
  19.     public  String getUserName() {  
  20.         return  userName;  
  21.     }  
  22.     public   void  setUserName(String userName) {  
  23.         this .userName = userName;  
  24.     }  
  25.     public  String getPassword() {  
  26.         return  password;  
  27.     }  
  28.     public   void  setPassword(String password) {  
  29.         this .password = password;  
  30.     }  
  31.     public  String getEmail() {  
  32.         return  email;  
  33.     }  
  34.     public   void  setEmail(String email) {  
  35.         this .email = email;  
  36.     }  
  37.       
  38.     public  String toString(){  
  39.         StringBuilder sb = new  StringBuilder();  
  40.           
  41.         sb.append(getClass()).append("[" )  
  42.         .append("userName=" ).append(userName).append( ", " )  
  43.         .append("password=" ).append(password).append( ", " )  
  44.         .append("email=" ).append(email).append( "]" );  
  45.           
  46.         return  sb.toString();  
  47.     }  
  48.       
  49. }  


2) Validate的触发
在需要校验的对象前增加 @Valid 注解 (该注解位于javax.validation包中)来触发校验。示例如下:

[java]  view plain copy
  1. /**  
  2.      * 处理提交的用户注册信息。  
  3.      * @param model  
  4.      * @return  
  5.      */   
  6.     @RequestMapping  (method = RequestMethod.POST)  
  7.     public  String doRegister( @Valid  User user, BindingResult result){  
  8.         if (logger.isDebugEnabled()){  
  9.             logger.debug("process url[/user], method[post] in " +getClass());  
  10.         }  
  11.         //校验没有通过   
  12.         if (result.hasErrors()){  
  13.             return   "user" ;  
  14.         }  
  15.           
  16.         if (user !=  null ){  
  17.             userService.saveUser(user);  
  18.         }  
  19.           
  20.         return   "user" ;  
  21.     }  


这样就可以完成针对输入数据User对象的校验了, 校验结果任然保存在BindingResult对象中。

 

 

 

校验方式二: Spring Validator 

1)Validator接口的实现:

Spring框架的Validator接口定义,

[java]  view plain copy
  1. package  org.springframework.validation;  
  2.   
  3. public   interface  Validator {  
  4.       
  5.     boolean  supports(Class<?> clazz);  
  6.       
  7.     void  validate(Object target, Errors errors);  
  8.   
  9. }  

要使用它进行校验必须实现该接口。实现Validator接口的代码如下:

[java]  view plain copy
  1. package  org.study.validation.validator;  
  2.   
  3. import  org.springframework.validation.Errors;  
  4. import  org.springframework.validation.ValidationUtils;  
  5. import  org.springframework.validation.Validator;  
  6. import  org.study.domain.User;  
  7.   
  8. public   class  UserValidator  implements  Validator {  
  9.   
  10.     @Override   
  11.     public   boolean  supports(Class<?> clazz) {  
  12.         return  clazz.equals(User. class );  
  13.     }  
  14.   
  15.     @Override   
  16.     public   void  validate(Object target, Errors errors) {  
  17.         ValidationUtils.rejectIfEmpty(errors, "userName" "user.userName.required" "用户名不能为空" );  
  18.         ValidationUtils.rejectIfEmpty(errors, "password" "user.password.required" "密码不能为空" );  
  19.         ValidationUtils.rejectIfEmpty(errors, "email" "user.email.required" "邮箱不能为空" );  
  20.         User user = (User)target;  
  21.         int  length = user.getUserName().length();  
  22.         if (length> 20 ){  
  23.             errors.rejectValue("userName" "user.userName.too_long" "用户名不能超过{20}个字符" );  
  24.         }  
  25.         length = user.getPassword().length();  
  26.         if (length < 6 ){  
  27.             errors.rejectValue("password" "user.password.too_short" "密码太短,不能少于{6}个字符" );  
  28.         }else   if (length> 20 ){  
  29.             errors.rejectValue("password" "user.password.too_long" "密码太长,不能长于{20}个字符" );  
  30.         }  
  31.         int  index = user.getEmail().indexOf( "@" );  
  32.         if (index == - 1 ){  
  33.             errors.rejectValue("email" "user.email.invalid_email" "邮箱格式错误" );  
  34.         }  
  35.     }  
  36.   
  37. }  


2) 设置Validator,并触发校验。
在我们的Controller中需要使用父类已有的方法来为DataBinder对象指定Validator,  protected initBinder(WebDataBinder binder); 代码如下:

[java]  view plain copy
  1. @InitBinder   
  2.     protected   void  initBinder(WebDataBinder binder){  
  3.         binder.setValidator(new  UserValidator());  
  4.     }  


为binder对象指定好Validator校验对象后,下面一步的就是在需要校验的时候触发validate方法,该触发步骤是通过 @Validated 注解(该注解是Spring框架定义的)实现的。

[java]  view plain copy
  1. /**  
  2.      * 处理提交的用户注册信息。  
  3.      * @param model  
  4.      * @return  
  5.      */   
  6.     @RequestMapping  (method = RequestMethod.POST)  
  7.     public  String doRegister( @Validated  User user, BindingResult result){  
  8.         if (logger.isDebugEnabled()){  
  9.             logger.debug("process url[/user], method[post] in " +getClass());  
  10.         }  
  11.         //校验没有通过   
  12.         if (result.hasErrors()){  
  13.             return   "user" ;  
  14.         }  
  15.           
  16.         if (user !=  null ){  
  17.             userService.saveUser(user);  
  18.         }  
  19.           
  20.         return   "user" ;  
  21.     }  


至此,从页面提交的User对象可以通过我们实现的UserValidator类来校验了,校验的结果信息存入BindingResult result对象中。在前台页面可以使用spring-form的标签<sf:errors path="*" />来显示。

分享到:
评论
1 楼 monical1 2013-10-24  
正用到了mvc,获益匪浅!

相关推荐

    Asp.net Mvc表单验证气泡提示效果

    本文实例为大家分享了Asp.net Mvc表单验证的制作代码,供大家参考,具体内容如下 将ASP.NET MVC或ASP.NET Core MVC的表单验证改成气泡提示: //新建一个js文件(如:jquery.validate.Bubble.js),在所有要验证的页面...

    ASPnet MVC教程 19.表单验证

    Aspnet Mvc教程 1.说明 01:06 Aspnet Mvc教程 2.准备工作 02:37 Aspnet Mvc教程 3....Aspnet Mvc教程 4....Aspnet Mvc教程 5....Aspnet Mvc教程 6.mvc理论讲解 03:53 Aspnet Mvc教程 7.ViewData 04:51 ...表单验证 10:50

    spring mvc服务端表单验证实例

    spring mvc服务端表单验证实例 能跑起来看效果 lib齐全 希望对您的学习有帮助

    详解ASP.NET MVC Form表单验证

    主要为大家详细介绍了ASP.NET MVC Form表单验证,一般验证方式有Windows验证和表单验证,web项目用得更多的是表单验证,感兴趣的小伙伴们可以参考一下

    SpringMVC使用Validation验证表单

    国外网站的例程,需要的童鞋请下载,比较有参考意义。

    mvc表单基本验证,前后台数据格式验证等.zip

    mvc表单基本验证,前后台数据格式验证等.zip

    基于ASP.NET Ajax框架实现表单验证编程原理

    基于ASP.NET Ajax框架实现表单验证编程原理

    源码:MVC中基于表单的用户身份验证与角色授权

    1.示例代码完整可用,具备在MVC使用表单身份验证,角色授权功能。 并且支持cookie加密。 2.为了方便教学,整个项目末连接数据库,将用户名及角色名称写死了。使用时,自行调用数据库即可。 3.实际使用时将cookie角色...

    Aspnet Mvc教程 16.表单生成及Post传值

    Aspnet Mvc教程 1.说明 01:06 Aspnet Mvc教程 2.准备工作 02:37 Aspnet Mvc教程 3....Aspnet Mvc教程 4....Aspnet Mvc教程 5....Aspnet Mvc教程 6.mvc理论讲解 03:53 Aspnet Mvc教程 7.ViewData 04:51 ...表单验证 10:50

    ASP.Net MVC教程 19 表单验证_标清

    ASP.Net MVC教程 19 表单验证_标清

    PHP表单验证类

    PHP表单验证类,不用自己再去去空格,直接通过form类,过滤非法字符

    MVC WebApi 用户权限验证及授权DEMO

    MVC WebApi 用户权限验证及授权DEMO 前言:Web 用户的身份验证,及页面操作权限验证是B/S系统的基础功能,一个功能复杂的业务应用系统,通过角色授权来控制用户访问,本文通过Form认证,Mvc的Controller基类及...

    Aspnet Mvc教程 5. 基本工作流程

    Aspnet Mvc教程 1.说明 01:06 Aspnet Mvc教程 2.准备工作 02:37 Aspnet Mvc教程 3....Aspnet Mvc教程 4....Aspnet Mvc教程 5....Aspnet Mvc教程 6.mvc理论讲解 03:53 Aspnet Mvc教程 7.ViewData 04:51 ...表单验证 10:50

    Aspnet Mvc教程 11.重定向、Redirect

    Aspnet Mvc教程 1.说明 01:06 Aspnet Mvc教程 2.准备工作 02:37 Aspnet Mvc教程 3....Aspnet Mvc教程 4....Aspnet Mvc教程 5....Aspnet Mvc教程 6.mvc理论讲解 03:53 Aspnet Mvc教程 7.ViewData 04:51 ...表单验证 10:50

    Aspnet Mvc教程 15.QueryString传值

    Aspnet Mvc教程 1.说明 01:06 Aspnet Mvc教程 2.准备工作 02:37 Aspnet Mvc教程 3....Aspnet Mvc教程 4....Aspnet Mvc教程 5....Aspnet Mvc教程 6.mvc理论讲解 03:53 Aspnet Mvc教程 7.ViewData 04:51 ...表单验证 10:50

    Aspnet Mvc教程 17.UpdateModel

    Aspnet Mvc教程 1.说明 01:06 Aspnet Mvc教程 2.准备工作 02:37 Aspnet Mvc教程 3....Aspnet Mvc教程 4....Aspnet Mvc教程 5....Aspnet Mvc教程 6.mvc理论讲解 03:53 Aspnet Mvc教程 7.ViewData 04:51 ...表单验证 10:50

    Aspnet Mvc教程 18.单选复选(更新)

    Aspnet Mvc教程 1.说明 01:06 Aspnet Mvc教程 2.准备工作 02:37 Aspnet Mvc教程 3....Aspnet Mvc教程 4....Aspnet Mvc教程 5....Aspnet Mvc教程 6.mvc理论讲解 03:53 Aspnet Mvc教程 7.ViewData 04:51 ...表单验证 10:50

Global site tag (gtag.js) - Google Analytics