转载

Spring MVC 之输入验证(六)

Spring MVC 验证主要还是用的是hibernate的验证。so需要添加以下的jar包:

1、 hibernate-validator-5.2.2.Final.jar

2、hibernate-validator-annotation-processor-5.2.2.Final.jar (这个可以不用)

3、 log4j.jar

4 、slf4j-api-1.5.6.jar

5、 slf4j-log4j12-1.5.6.jar

6 、validation-api-1.1.0.Final.jar

以登录验证为例:

在实体属性上配置注解;

 package com.cy.springannotation.entity;   import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern;  import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty;  /**  * 定义一个表单实体类  * @author acer  *  */ public class UserBean {     //要求属性名必须要和表单的参数名一样的!      @NotEmpty(message="用户名不能为空!")     @Pattern(regexp="//w{6,20}",message="用户名6-20位")     private String username;          @NotEmpty(message="密码不能为空")     @Length(max=20,min=6,message="密码不能小于6位")     private String password;          public String getUsername() {         return username;     }     public void setUsername(String username) {         this.username = username;     }     public String getPassword() {         return password;     }     public void setPassword(String password) {         this.password = password;     }       } 

JSP页面上通过spring标记来获取错误信息:

  1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>  2 <%  3 String path = request.getContextPath();  4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  5 %>  6 <!-- srpingmvc 验证需要使用到spring表单标签 -->  7 <%@ taglib prefix="springform" uri="http://www.springframework.org/tags/form" %>  8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  9 <html> 10   <head> 11     <base href="<%=basePath%>"> 12      13     <title>验证页面</title> 14      15     <meta http-equiv="pragma" content="no-cache"> 16     <meta http-equiv="cache-control" content="no-cache"> 17     <meta http-equiv="expires" content="0">     18     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 19     <meta http-equiv="description" content="This is my page"> 20     <!-- 21     <link rel="stylesheet" type="text/css" href="styles.css"> 22     --> 23  24   </head> 25    26   <body> 27    28    <!-- commandName用于指定活动的Bean对象,即我可以在页面上,获取对象属性所对应的错误信息,值是对象名称的首字母小写,同modelAttribute一样的意思(modelAttribute="contentModel") --> 29   <!--  <springform:form method="post" action="login.do" commandName="userBean"> --> 30    <springform:form method="post" action="login.do" modelAttribute="user"> 31   32     <table> 33        <tr> 34            <td>用户名:</td> 35            <td><input type="text" name="username"/><springform:errors delimiter="," path="username"></springform:errors></td> 36        </tr> 37         <tr> 38            <td>密码</td> 39            <td><input type="text" name="password"/><springform:errors delimiter="," path="password"></springform:errors></td> 40        </tr>  41        <tr> 42            <td colspan="2"> <input type="submit" value="提交"/> </td> 43        </tr> 44     </table> 45 </springform:form> 46   </body> 47 </html> 

delimiter:如果一个属性有多个错误,错误信息的分隔符。默认是换行.

path:验证失败的属性名.

控制器:

  1 @RequestMapping(value="/login.do")  2     //@Valid 通过该注解告知该方法,我的哪个实体Bean需要验证  3     //BindingResult 为固定参数,用于接收验证结果  4       5     public String login(@ModelAttribute("user") @Valid UserBean user,BindingResult br) {  6         if(br.hasErrors()){  7             //验证未通过则  8             return "validate1";  9         } 10         log.info(user.getUsername()); 11         log.info(user.getPassword()); 12          13         return "index"; 14     } 

如果界面上使用了spring标签,那么需要预先启动Spring容器,所以在web.xml中增加配置:

  1 <!-- 启动spring容器,用于支持springmvc validate -->  2   <context-param>  3     <param-name>contextConfigLocation</param-name>  4     <param-value>/WEB-INF/classes/springAnnotation-servlet.xml</param-value>  5 </context-param>  6   7 <!-- 配置在context-param里面文件内的内容,需要通过 ContextLoaderListener添加到上下文里面去-->  8   <listener>  9     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 10   </listener> 

到springAnnotation-servlet.xml文件中配置:

 1 <!-- 开启注解这里需要添加个validator--> 2 <!--开启注解  -->     3 <mvc:annotation-driven conversion-service="tc" validator="validator" /> 4  5 <!-- 验证配置,告知srpingmvc,我使用的是Hibernate验证框架来完成的验证 --> 6     <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> 7         <property name="providerClass" value="org.hibernate.validator.HibernateValidator" /> 8     </bean> 

显示测试:

进入登录页面

Spring MVC 之输入验证(六)

直接点击提交:

Spring MVC 之输入验证(六)

原文  http://www.cnblogs.com/hellokitty1/p/5167839.html
正文到此结束
Loading...