SpringMvc的消息验证

来源:互联网 发布:淘宝如何给差评 编辑:程序博客网 时间:2024/06/14 08:17

web.xml的代码

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.     <!-- 加载spring配置 -->  
  8.     <context-param>  
  9.         <param-name>contextConfigLocation</param-name>  
  10.         <param-value>classpath:/spring.xml</param-value>  
  11.     </context-param>  
  12.     <listener>  
  13.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  14.     </listener>  
  15.     <!-- 这是加载springmvc的配置 -->  
  16.     <!-- spring自带的解决乱码的过滤器 -->  
  17.         <filter>  
  18.         <filter-name>utf</filter-name>  
  19.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  20.         <init-param>  
  21.             <param-name>encoding</param-name>  
  22.             <param-value>UTF-8</param-value>  
  23.         </init-param>  
  24.     </filter>  
  25.     <filter-mapping>  
  26.         <filter-name>utf</filter-name>  
  27.         <url-pattern>/*</url-pattern>  
  28.     </filter-mapping>  
  29.     <filter>  
  30.     <!-- 配置这个selevlet来加载sprinmvc的配置文件 -->  
  31.     <filter-name>hidden</filter-name>  
  32.     <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>  
  33.   </filter>      
  34.   <filter-mapping>  
  35.     <filter-name>hidden</filter-name>  
  36.     <url-pattern>/*</url-pattern>  
  37.   </filter-mapping>  
  38.     <servlet>  
  39.         <servlet-name>springmvc</servlet-name>  
  40.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  41.         <!-- 通过这个参数去找配置文件 不加这个参数默认在 /WEB-INF/找spservlet-name-servlet.xml这个文件-->  
  42.         <init-param>  
  43.             <param-name>contextConfigLocation</param-name>  
  44.             <param-value>classpath:/springmvc.xml</param-value>  
  45.         </init-param>  
  46.         <!-- 启动tomcat的时候就加载 -->  
  47.         <load-on-startup>0</load-on-startup>  
  48.     </servlet>  
  49.     <servlet-mapping>  
  50.         <servlet-name>springmvc</servlet-name>  
  51.         <!-- /拦截所有以.action -->  
  52.         <url-pattern>*.action</url-pattern>  
  53.         <!-- /拦截所有servlet -->  
  54.         <url-pattern>/</url-pattern>  
  55.     </servlet-mapping>  
  56.   <welcome-file-list>  
  57.     <welcome-file>index.jsp</welcome-file>  
  58.   </welcome-file-list>  
  59. </web-app>  


spring配置文件的代码

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans  
  3.     xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xmlns:p="http://www.springframework.org/schema/p"  
  6.     xmlns:context="http://www.springframework.org/schema/context"  
  7.     xmlns:tx="http://www.springframework.org/schema/tx"  
  8.     xmlns:aop="http://www.springframework.org/schema/aop"  
  9.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  10.       
  11.     xsi:schemaLocation="  
  12.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  13.     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd  
  14.     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd  
  15.     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd  
  16.     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd  
  17.     ">  
  18.     <!-- 加载消息源 因为是spring的所以只能写在spring的配置文件中-->  
  19.     <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
[html] view plain copy
  1. <span style="white-space:pre">  </span><!-- 把消息国际化的basename注入进来 -->  
  2.         <property name="basename" value="classpath:/my"></property>  
  3.     </bean>  
  4.       
  5.     </beans>  

springmvc 的配置文件

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <beans  
  4.     xmlns="http://www.springframework.org/schema/beans"  
  5.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  6.     xmlns:p="http://www.springframework.org/schema/p"  
  7.     xmlns:context="http://www.springframework.org/schema/context"  
  8.     xmlns:tx="http://www.springframework.org/schema/tx"  
  9.     xmlns:aop="http://www.springframework.org/schema/aop"  
  10.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  11.       
  12.     xsi:schemaLocation="  
  13.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  14.     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd  
  15.     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd  
  16.     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd  
  17.     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd  
  18.     ">  
  19.     <!-- 配置扫描 -->  
  20.     <context:component-scan base-package="cn.et"></context:component-scan>  
  21.     <!-- 通过这个类加载spring消息源才能在实体类中用消息国际化 (验证器) -->  
  22.     <bean id="myMessage" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">  
  23.         <!-- 把spring的消息源注入进来 -->  
  24.         <property name="validationMessageSource" ref="messageSource"></property>  
  25.     </bean>  
  26. <span style="white-space:pre">  </span>   
  27.   <span style="white-space:pre">    </span> <!--告诉tomcat用这个验证器 -->  
  28.    <span style="white-space:pre">   </span><mvc:annotation-driven validator="myMessage">  
  29.    <span style="white-space:pre">   </span></mvc:annotation-driven>  
  30. </beans>  

action的代码
验证消息同时处理多个对象BindingResult跟在对象后面即可。
Errors是BindingResult的父接口,效果一样,只是不能new FieldError();


[java] view plain copy
  1. @Controller  
  2. @RequestMapping("/day0602")  
  3. public class VaildatorAction{  
  4.     @Autowired  
  5.     private MessageSource source;  
[java] view plain copy
  1. <span style="white-space:pre">  /** 
  2.     * 必须要添加@Valid注解,不加不会进行声明式验证 
  3.     *  
  4.     * 当@valid注解标示的实体类验证失败后 
  5.     * 所有的错误消息都被注入到BindingResult对象中 
  6.     *  
  7.     * 在显示错误时springmvc标签的path由对象名(类名的第一个字母小写).属性名 
  8.     *  
  9.     * @ModelAttribute("user")可以修改对象名 
  10.     *  
  11.     * @param user 
  12.     * @return 
  13.     */</span>  
[java] view plain copy
  1. @RequestMapping("/vaildator.action")  
  2. //@ModelAttribute("user")可以通过这个改名字默认首字母小写 还会传到jsp界面 request  BindingResult是注入错误消息的对象   
  3. public String vaildator(@ModelAttribute("user"@Valid UserinfoEntity user,BindingResult bindingResult,Locale locale,HttpServletRequest request){  
  4.     //代码验证  验证密码与在此输入密码  
[java] view plain copy
  1. <span style="white-space:pre">      </span>if(!user.getPassword().equals(user.getRepassword())){  
  2.             //获取国际化的消息  
  3.             String str=source.getMessage("notpassword"null,locale);  
  4.             //注入到错误消息对象  
  5.              bindingResult.addError(new FieldError("repassword"null, str));  
  6.         }  
  7.         //验证不通过返回  
  8.         if(bindingResult.hasErrors()){  
  9.             return "/day20170602/vaildator.jsp";  
  10.         }  
  11.         request.setAttribute("birthday",new SimpleDateFormat("yyyy-MM-dd").format(user.getBirthday()));  
  12.         return "/day20170602/suc.jsp";  
  13.     }  
  14. }  


实体类中的代码

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint

使用hibernate validator出现上面的错误, 需要 注意


@NotNull 和 @NotEmpty  和@NotBlank 区别


@NotEmpty 用在集合类上面
@NotBlank 用在String上面
@NotNull    用在基本类型上


如果在基本类型上面用NotEmpty或者NotBlank 会出现上面的错


[java] view plain copy
  1. public class UserinfoEntity {  
  2.     @NotBlank(message="{notEmpty}")  
  3.     private String userName;  
  4.       
  5.     @NotBlank(message="{notEmpty}")  
  6.     private String password;  
  7.       
  8.     @NotBlank(message="{notEmpty}")  
  9.     private String repassword;  
  10.       
  11.     @NotBlank(message="{notEmpty}")  
  12.     private String location;  
  13.       
  14.     @NotNull(message="{notEmpty}")  
  15.     @DateTimeFormat(pattern="yyyy-MM-dd")  
  16.     @Past(message="{dates}")  
  17.     private Date birthday;  
  18.       
  19.     @NotBlank(message="{notEmpty}")  
  20.     @Email(message="{emailnot}")  
  21.     private String email;  
  22.       
  23.     @NotBlank(message="{notEmpty}")  
  24.     @Pattern(regexp="^[0-9]{17}([0-9]|x|X)$",message="{cidnot}")  
  25.     private String userid;  
  26.       
  27.     @NotBlank(message="{notEmpty}")  
  28.     @Pattern(regexp="^[0-9]{11}",message="{phonenot}")  
  29.     private String phone;  
  30.       
  31.     @URL(message="{urls}")  
  32.     @NotBlank(message="{notEmpty}")  
  33.     private String url;  
  34.     public String getRepassword() {  
  35.         return repassword;  
  36.     }  


jsp的代码

把jsp界面日期类型转换成字符串

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>   

<fmt:formatDate value="${user.birthday }" pattern="yyyy-MM-dd HH:mm:ss"/>  


[html] view plain copy
  1. <%@ page language="java" contentType="text/html; charset=utf-8"  
  2.     pageEncoding="utf-8"%>  
  3.     <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
  4.     <%@taglib uri="http://www.springframework.org/tags" prefix="t"%>  
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  6. <html>  
  7. <head>  
  8. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
  9. <title>Insert title here</title>  
  10. </head>  
  11. <body>  
  12.     <form action="${pageContext.request.contextPath}/day0602/vaildator.action"  method="post">  
  13.         <t:message code="userName"></t:message><input type="text" name="userName"/>  
  14.             <font color="red"><form:errors path="user.userName"></form:errors></font><br/>  
  15.         <t:message code="password"></t:message><input type="password" name="password"/>  
  16.             <font color="red"><form:errors path="user.password"></form:errors></font><br/>  
  17.         <t:message code="agpassword"></t:message><input type="password" name="repassword"/>  
  18.             <font color="red"><form:errors path="user.repassword"></form:errors></font><br/>  
  19.         <t:message code="sex"></t:message><input type="radio" name="sex" value="0" checked/>  
  20.                 <t:message code="man"></t:message><input type="radio" name="sex" value="1" />  
  21.                 <t:message code="woman"></t:message><br/>  
  22.         <t:message code="birthday"></t:message><input type="text" name="birthday"/>  
  23.             <font color="red"><form:errors path="user.birthday"></form:errors></font><br/>  
  24.         <t:message code="location"></t:message><input type="text" name="location"/>  
  25.             <font color="red"><form:errors path="user.location"></form:errors></font><br/>  
  26.         <t:message code="phone"></t:message><input type="text" name="phone"/>  
  27.             <font color="red"><form:errors path="user.phone"></form:errors></font><br/>  
  28.         <t:message code="userid"></t:message><input type="text" name="userid"/>  
  29.             <font color="red"><form:errors path="user.userid"></form:errors></font><br/>  
  30.         <t:message code="email"></t:message><input type="text" name="email"/>  
  31.             <font color="red"><form:errors path="user.email"></form:errors></font><br/>  
  32.         <t:message code="url"></t:message><input type="text" name="url"/>  
  33.             <font color="red"><form:errors path="user.url"></form:errors></font><br/>  
  34.         <input type="submit" value="<t:message code="submit"></t:message>"/><br/>  
  35.     </form>  
  36. </body>  
  37. </html>  


Spring 3.0拥有自己独立的数据校验框架,同时支持JSR 303标准的校验框架。Spring 的DataBinder在进行数据绑定时,可同时调用校验框架完成数据校验工作。在Spring MVC中,则可直接通过注解驱动的方式进行数据校验。
       Spring的org.springframework.validation是校验框架所在的包

<mvc:annotation-driven/>会默认装配好一个LocalValidatorFactoryBean,通过在处理方法的入参上标注@Valid注解即可让spring MVC在完成数据绑定后执行数据校验的工作。



注    解功能说明
@Null被注释的元素必须为 null
@NotNull被注释的元素必须不为 null
@AssertTrue被注释的元素必须为 true
@AssertFalse被注释的元素必须为 false
@Min(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value)被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value)被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max, min)被注释的元素的大小必须在指定的范围内
@Digits (integer, fraction)被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past被注释的元素必须是一个过去的日期
@Future被注释的元素必须是一个将来的日期

hibernate-validator-4.3.2.Final架包的下载地址:

https://sourceforge.net/projects/hibernate/?source=typ_redirect

 

必需导入的四个包:

hibernate-validator-4.3.2.Final.jar

hibernate-validator-annotation-processor-4.3.2.Final.jar

jboss-logging-3.1.0.CR2.jar

validation-api-1.0.0.GA.jar