Spring Validation(使用Hibernate Validator)

1、需要的jar包

hibernate-validator.5.1.3.Final.jar

validation-api.1.1.0.Final.jar

2、springsevlet-config.xml配置

在spring3之后,任何支持JSR303的validator(如Hibernate Validator)都可以通过简单配置引入,只需要在配置xml中加入,这时validatemessage的属性文件默认为classpath下的ValidationMessages.properties

<!-- support JSR303 annotation if JSR 303 validation present on classpath -->
<mvc:annotation-driven />

如果不使用默认,可以使用下面配置:

<mvc:annotation-driven validator="validator" />

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="providerClass"  value="org.hibernate.validator.HibernateValidator"/>
    <!--不设置则默认为classpath下的ValidationMessages.properties -->
    <property name="validationMessageSource" ref="validatemessageSource"/>
</bean>
<bean id="validatemessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="classpath:validatemessages"/> <property name="fileEncodings" value="utf-8"/> <property name="cacheSeconds" value="120"/> </bean>

 3、hibernate validator constraint 注解

Bean Validation 中内置的 constraint         
@Null   被注释的元素必须为 null    
@NotNull    被注释的元素必须不为 null    
@AssertTrue     被注释的元素必须为 true    
@AssertFalse    被注释的元素必须为 false    
@Min(value)     被注释的元素必须是一个数字,其值必须大于等于指定的最小值    
@Max(value)     被注释的元素必须是一个数字,其值必须小于等于指定的最大值    
@DecimalMin(value)  被注释的元素必须是一个数字,其值必须大于等于指定的最小值    
@DecimalMax(value)  被注释的元素必须是一个数字,其值必须小于等于指定的最大值    
@Size(max=, min=)   被注释的元素的大小必须在指定的范围内    
@Digits (integer, fraction)     被注释的元素必须是一个数字,其值必须在可接受的范围内    
@Past   被注释的元素必须是一个过去的日期    
@Future     被注释的元素必须是一个将来的日期    
@Pattern(regex=,flag=)  被注释的元素必须符合指定的正则表达式    
    
Hibernate Validator 附加的 constraint    
@NotBlank(message =)   验证字符串非null,且长度必须大于0    
@Email  被注释的元素必须是电子邮箱地址    
@Length(min=,max=)  被注释的字符串的大小必须在指定的范围内    
@NotEmpty   被注释的字符串的必须非空    
@Range(min=,max=,message=)  被注释的元素必须在合适的范围内 

 4、使用validator

在需要校验的对象前增加@Valid 注解(该注解位于javax.validation包中)来触发校验。这样就可以完成针对输入数据User对象的校验了,校验结果任然保存在BindingResult对象中。

 1 package com.mkyong.common.model;
 2  
 3 import org.hibernate.validator.constraints.NotEmpty;
 4 import org.hibernate.validator.constraints.Range;
 5  
 6 public class Customer {
 7  
 8     @NotEmpty //make sure name is not empty
 9     String name;
10  
11     @Range(min = 1, max = 150) //age need between 1 and 150
12     int age;
13  
14     //getter and setter methods
15  
16 }
 1 package com.mkyong.common.controller;
 2  
 3 import javax.validation.Valid;
 4 import org.springframework.stereotype.Controller;
 5 import org.springframework.ui.ModelMap;
 6 import org.springframework.validation.BindingResult;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RequestMethod;
 9 import com.mkyong.common.model.Customer;
10  
11 @Controller
12 @RequestMapping("/customer")
13 public class SignUpController {
14  
15     @RequestMapping(value = "/signup", method = RequestMethod.POST)
16     public String addCustomer(@Valid Customer customer, BindingResult result) {
17  
18         if (result.hasErrors()) {
19             return "SignUpForm";
20         } else {
21             return "Done";
22         }
23  
24     }
25  
26     @RequestMapping(method = RequestMethod.GET)
27     public String displayCustomerForm(ModelMap model) {
28  
29         model.addAttribute("customer", new Customer());
30         return "SignUpForm";
31  
32     }
33  
34 }
 1 <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
 2 <html>
 3 <head>
 4 <style>
 5 .error {
 6     color: #ff0000;
 7 }
 8  
 9 .errorblock {
10     color: #000;
11     background-color: #ffEEEE;
12     border: 3px solid #ff0000;
13     padding: 8px;
14     margin: 16px;
15 }
16 </style>
17 </head>
18  
19 <body>
20     <h2>Customer SignUp Form - JSR303 @Valid example</h2>
21  
22     <form:form method="POST" commandName="customer" action="customer/signup">
23         <form:errors path="*" cssClass="errorblock" element="div" />
24         <table>
25             <tr>
26                 <td>Customer Name :</td>
27                 <td><form:input path="name" /></td>
28                 <td><form:errors path="name" cssClass="error" /></td>
29             </tr>
30             <tr>
31                 <td>Customer Age :</td>
32                 <td><form:input path="age" /></td>
33                 <td><form:errors path="age" cssClass="error" /></td>
34             </tr>
35             <tr>
36                 <td colspan="3"><input type="submit" /></td>
37             </tr>
38         </table>
39     </form:form>
40  
41 </body>
42 </html>

可以通过定义“validatemessage.properties”文件,覆盖定义在持久化对象上的错误提示,通常属性文件中属性key为“@Annotation Name.object.fieldname“的形式:

NotEmpty.customer.name = Name is required!
Range.customer.age = Age value must be between 1 and 150

代码运行Demo:

SpringMVC-Bean-Validation-JSR303-Example-2.zip

5、参考

http://www.mkyong.com/spring-mvc/spring-3-mvc-and-jsr303-valid-example/

http://www.cnblogs.com/myitmylife/p/3617084.html

http://www.cnblogs.com/liukemng/p/3738055.html

posted @ 2015-02-25 20:55  添哥  阅读(31520)  评论(0编辑  收藏  举报