`
kobe学java
  • 浏览: 248332 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

spring mvc 注解验证springmodules common validator (注解验证)

 
阅读更多

转载:http://blog.csdn.net/h396071018/article/details/6658962

spring mvc 注解验证springmodules common validator (注解验证)

分类: java 634人阅读 评论(0) 收藏 举报

 首先说spring modules, 它是为spring定制的一些工具组件,官方地址在https://springmodules.dev.java.net/, 官网上是这样介绍的:Spring Modules is a collection of tools, add-ons and modules to extend the Spring Framework. The core goal of Spring Modules is to facilitate integration between Spring and other projects without cluttering or expanding the Spring core. 里面有很多子项目。其中commons validator是一个可配置的验证框架,使用方式和工作原理都和struts用的ValidatorPlugIn一样。它可以通过配置生成js在客户端验证, 也可以配合具有验证功能的spring controller实现server端验证.

 我做得一个小例子在我的资源里大家可以下载http://download.csdn.net/source/3494112

项目是用eclipse做得包含了所有的jar包和文件直接运行即可

1 从https://springmodules.dev.java.net/下载jar包,我们将使用里面的spring-modules-validation.jar;


2 我使用的IDE是eclipse 新建一个web project名字叫做:springValdiateAnonation, 拷贝spring,jakarta-commons等相关的必要jar文件包括spring-modules-validation.jar到WEB-INF/lib/,拷贝c-rt.tld, spring.tld, spring-form.tld到WEB-INF/tld/;做好spring的基础配置工作,包括web.xml, applicationContext.xml, xxx-servlet.xml; 配置好log4j.properties;

3 在src下新建包web.kjt 在该包下建域对象User, 将作为我们的表单对象;

[java] view plaincopy
  1. public class User {  
  2. private String userName;  
  3. private String password;  
  4. public String getUserName() {  
  5. return userName;  
  6. }  
  7. public void setUserName(String userName) {  
  8. this.userName = userName;  
  9. }  
  10. public String getPassword() {  
  11. return password;  
  12. }  
  13. public void setPassword(String password) {  
  14. this.password = password;  
  15. }  
  16.   
  17. }  

4 在web.kjt包下新建一个LoginController,因为使用spring mvc注解配置请求信息,所有就不用继承相应的controller,代码如下

[java] view plaincopy
  1. package com.kjt;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import javax.validation.Valid;  
  7.   
  8. import org.springframework.beans.factory.annotation.Autowired;  
  9. import org.springframework.stereotype.Controller;  
  10.   
  11. import org.springframework.ui.ModelMap;  
  12. import org.springframework.validation.BindingResult;  
  13. import org.springframework.validation.Validator;  
  14.   
  15.   
  16. import org.springframework.web.bind.annotation.ModelAttribute;  
  17. import org.springframework.web.bind.annotation.RequestMapping;  
  18.   
  19. @Controller  
  20. public class LoginController {  
  21.       
  22.     @Autowired(required=false)  
  23.     Validator validator;    //这个需要在applicationContext.xml中配置bean注射进来  
  24.     //客户端验证和后台验证配置的请求  
  25.     @RequestMapping("/login.do")  
  26.     public String login(@Valid @ModelAttribute("user")User user,BindingResult bindingResult,ModelMap modelMap){  
  27.         try {  
  28.             System.out.println("11");//看请求能否进来  
  29.             if (user.getUserName() ==null) {  
  30.                 user=new User();  
  31.                 modelMap.addAttribute(user);  
  32.             }  
  33.             else {  
  34.                 validator.validate(user, bindingResult);//这个是对前台提交的数据进行验证  
  35.             }  
  36.               
  37.             return"login";  
  38.         } catch (Exception e) {  
  39.             // TODO: handle exception  
  40.             System.out.println("错误信息"+e.getMessage());  
  41.             e.printStackTrace();  
  42.             return "welcome";  
  43.         }  
  44.           
  45.     }  
  46.     @RequestMapping(value="/login1.do")//后台验证配置的请求  
  47.     public String login1(@Valid @ModelAttribute("user")User user,BindingResult bindingResult,ModelMap modelMap){  
  48.         try {  
  49.             System.out.println("22");  
  50.             if (user.getUserName() ==null) {  
  51.                 user=new User();  
  52.                 modelMap.addAttribute(user);  
  53.             }  
  54.             else {  
  55.                 validator.validate(user, bindingResult);  
  56.             }  
  57.               
  58.             return"login1";  
  59.         } catch (Exception e) {  
  60.             // TODO: handle exception  
  61.             System.out.println("错误信息"+e.getMessage());  
  62.             e.printStackTrace();  
  63.             return "welcome";  
  64.         }  
  65.           
  66.     }  
  67. }  

需要说明的是User user,BindingResult bindingResult 这两个对象必须紧挨着,否则出错哦。他们bindingresult是把验证的错误信息存进他得errors属性里了

下面主要讲解springmvc 注解验证怎么配置,其实和springmvc xml验证没什么不同,就是配置请求方式不一样了

5 从springmodules下载包的sample中找validator-rules.xml,validation.xml拷贝到WEB-INF目录下, 打开观察一下这两个文件,你会发现他们和struts的validatorPlugin需要的两个配置文件一模一样 , 你甚至可以从你的struts项目中拷贝这两个文件拿过来修改修改即可工作.

 

validator-rules.xml预定义了一些验证器,比如required(必填项),minlength(最短长度), maxlength(最大长度), float(可输入小数),integer(可输入整数),mask(输入值要满足正则表达式要求), 这个文件大多数时候都不需要我们更改他们,除非为了拓展功能或者发现bug;

validation.xml定义了一些表单的验证规则,我们需要一个表单的验证功能就要在这个文件中配置一条验证信息. 这两个文件拷贝过来之后就可以配置验证器工厂和验证器了.

applicationContext.xml中配置validatorFactorybeanValidator(为什么要在applicationContext中配置: 因为验证器可作为应用程序公用的组件,可以被所有的servlet共享):

[java] view plaincopy
  1. <!--   
  2.              名字必须为messageSource,因为springmodules的jar包需要引用验证时需要引用名字为messageSource的bean  
  3.              你可以试验一下把名字改,我试验之后是不是这个名字 前台显示的错误信息validator-rules.xml最上面注释掉的Validator Error Messages的key  
  4.     -->  
  5.     <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">  
  6.         <property name="basename" value="messages" />  
  7.     </bean>  
  8.       
  9.     <bean id="validatorFactory" class="org.springmodules.validation.commons.DefaultValidatorFactory">  
  10.         <property name="validationConfigLocations">  
  11.             <list>  
  12.                 <value>WEB-INF/validator-rules.xml</value>  
  13.                 <value>WEB-INF/validation.xml</value>  
  14.             </list>  
  15.         </property>  
  16.     </bean>  
  17.     <!--  
  18.         在applicationContext.xml中配置validatorFactory和beanValidator  
  19.       
  20.         (为什么要在applicationContext中配置: 因为验证器可作为应用程序公用的组件,可以被所有的servlet共享):  
  21.     -->  
  22.     <bean id="beanValidator" class="org.springmodules.validation.commons.DefaultBeanValidator">  
  23.         <property name="validatorFactory" ref="validatorFactory"/>  
  24.     </bean>  
  25.       
  26.     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  27.         <property name="prefix" value="WEB-INF/jsp/" />  
  28.         <property name="suffix" value=".jsp" />  
  29.     </bean>  


6 打开validation.xml,在里面添加一个form,

[java] view plaincopy
  1. <form name="user">  
  2.             <field property="userName" depends="required"><!--depands 字段是配置需要满足的验证器,可配置多个-->  
  3.                 <!--  
  4.                     arg0是该字段的显示名,用于验证失败时显示提示信息  
  5.                       
  6.                     key是定义在messageResource中的消息的key                
  7.                 -->  
  8.                 <arg0 key="用户名" />  
  9.             </field>  
  10.             <field property="password" depends="maxlength,required">  
  11.                 <arg0 key="密码" />  
  12.                 <arg1 name="maxlength" key="${var:maxlength}" resource="false" />  
  13.                 <var>  
  14.                     <var-name>maxlength</var-name>  
  15.                     <var-value>10</var-value>  
  16.                 </var>  
  17.             </field>  
  18.         </form>  


7 配置需要的message, 为了在验证没通过时显示出错信息, 需要把示例文件validator-rules.xml最上面注释掉的Validator Error Messages拷贝到message.properties中,并且把它放在classpath下.同时需要在applicationContext.xml中配置messageSource,

[html] view plaincopy
  1. <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">  
  2.         <property name="basename" value="messages" />  
  3.     </bean>  


同时在message.properties中添加form字段的显示名称, 则本例的messages.properties全文如下:

[java] view plaincopy
  1. #english message file  
  2. errors.required={0} is required.  
  3. errors.minlength={0} can not be less than {1} characters.  
  4. errors.maxlength={0} can not be greater than {1} characters.  
  5. errors.invalid={0} is invalid.  
  6.   
  7. errors.byte={0} must be a byte.  
  8. errors.short={0} must be a short.  
  9. errors.integer={0} must be an integer.  
  10. errors.long={0} must be a long.  
  11. errors.float={0} must be a float.  
  12. errors.double={0} must be a double.  
  13.   
  14. errors.date={0} is not a date.  
  15. errors.range={0} is not in the range {1} through {2}.  
  16. errors.creditcard={0} is an invalid credit card number.  
  17. errors.email={0} is an invalid e-mail address.  
  18.   
  19. common.messages.close=Close   
  20.   
  21. user.name=userName  
  22. user.password=userPassword  


8 编辑jsp表单页面login.jsp,

[html] view plaincopy
  1. <%@ page language="java" contentType="text/html; charset=GB18030"    pageEncoding="GB18030"%>  
  2. <%@ taglib uri="/WEB-INF/tld/c-rt.tld" prefix="c"%>  
  3. <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>  
  4. <%@ taglib uri="/WEB-INF/tld/spring-form.tld" prefix="form"%>  
  5. <%@ taglib uri="http://www.springmodules.org/tags/commons-validator" prefix="validator" %>  
  6. <validator:javascript formName="user" staticJavascript="true" xhtml="true" cdata="false" />  
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  8. <html>  
  9. <head>  
  10. <meta http-equiv="Content-Type" content="text/html; charset=GB18030">  
  11. <title>登录页面</title>  
  12. </head>  
  13. <body>  
  14. <h1>欢迎访问,登录页面</h1>  
  15. <form action="login.do" method="post" id="user" name="user" onsubmit="return validateUser(this);">  
  16.     <table>  
  17.         <tr>  
  18.             <td>  
  19.                 用户名:  
  20.             </td>  
  21.             <td>  
  22.                 <spring:bind path="user.userName">  
  23.                     <input type="text" id="userName" name="userName" value="${status.value}"/>  
  24.                     <font color="red"><c:out value="${status.errorMessage}"/></font>  
  25.                 </spring:bind>  
  26.                   
  27.             </td>  
  28.         </tr>  
  29.         <tr>  
  30.             <td>  
  31.                 密码:  
  32.             </td>  
  33.             <td>  
  34.                 <spring:bind path="user.password">  
  35.                     <input type="text" id="password" name="password" value="${status.value}"/>  
  36.                     <font color="red"><c:out value="${status.errorMessage}"/></font>  
  37.                 </spring:bind>  
  38.             </td>  
  39.         </tr>  
  40.         <tr>  
  41.             <td>  
  42.                 <input type="submit"  value="登录" >  
  43.             </td>  
  44.             <td></td>  
  45.         </tr>  
  46.     </table>  
  47. </form>  
  48. </body>  
  49. </html>  

上面的配置是javascript和后台一起验证的

启动javascript验证在页首需要加入

<validator:javascript formName="book" staticJavascript="true" xhtml="true" cdata="false" />

部署到tomcat并测试:http://localhost:8080/springValdiateAnonation/login.do

后台验证界面

 

客户端验证界面

 

 我做得一个小例子在我的资源里大家可以下载http://download.csdn.net/source/3494112

项目是用eclipse做得包含了所有的jar包和文件直接运行即可

 

本文参考:http://blog.csdn.net/sunxing007/article/details/4660262

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics