Spring Validation (using Hibernate Validator)

Source: Internet
Author: User

1. Required JAR Package

Hibernate-validator.5.1.3.final.jar

Validation-api.1.1.0.final.jar

2. Springsevlet-config.xml Configuration

After Spring3, any JSR303-enabled Validator, such as Hibernate Validator, can be introduced through a simple configuration that only needs to be included in the configuration XML. At this point the Validatemessage property file defaults to Validationmessages.properties under Classpath:

</>

If you do not use the default, you can use the following configuration:

<Mvc:annotation-drivenValidator= "Validator" /><BeanID= "Validator"class= "Org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">    < Propertyname= "Providerclass"value= "Org.hibernate.validator.HibernateValidator"/>    <!--do not set defaults to validationmessages.properties under Classpath -    < Propertyname= "Validationmessagesource"ref= "Validatemessagesource"/></Bean>
<BeanID= "Validatemessagesource"class= "Org.springframework.context.support.ReloadableResourceBundleMessageSource"> < Propertyname= "BaseName"value= "Classpath:validatemessages"/> < Propertyname= "Fileencodings"value= "Utf-8"/> < Propertyname= "Cacheseconds"value= "+"/> </Bean>

3. Hibernate validator Constraint Annotations

The  constraint that is built into the Bean Validation @Null The annotated element must beNULL@NotNull The annotated element must not beNULL@AssertTrue The annotated element must be atrue@AssertFalse The annotated element must be afalse@Min (value) The annotated element must be a number whose value must be greater than or equal to the specified minimum value @Max (value) The annotated element must be a number whose value must be less than or equal to the specified maximum value @DecimalMin (value) The annotated element must be a number whose value must be greater than or equal to the specified minimum value @DecimalMax (value) the element being commented on must be a number whose value must be less than or equal to the specified maximum value @Size (Max=, min=The size of the annotated element must be within the specified range @Digits (integer, fraction) The annotated element must be a number whose value must be within an acceptable range @Past the annotated element must be a past date @F Uture The annotated element must be a future date @Pattern (Regex=,flag=The annotated element must conform to the specified regular expression Hibernate Validator additional constraint @NotBlank (Message=Verify that the string is not NULL, and that the length must be greater than 0 @Email The annotated element must be an e-mail address @Length (min=,max=The size of the annotated string must be within the specified range @NotEmpty the annotated string must be non-empty @Range (min=,max=,message=) The annotated element must be within the appropriate range

4. Using Validator

Add the @valid annotation (which is in the Javax.validation package) to trigger the checksum before the object that needs validation. This completes the validation of the user object for the input data, and the result of the validation is still stored in the Bindingresult object.

1  PackageCom.mkyong.common.model;2  3 ImportOrg.hibernate.validator.constraints.NotEmpty;4 ImportOrg.hibernate.validator.constraints.Range;5  6  Public classCustomer {7  8@NotEmpty//Make sure name was not empty9 String name;Ten   One@Range (min = 1, max = 150)//Age need between 1 and A     intAge ; -   -     //getter and Setter methods the   -}
1  PackageCom.mkyong.common.controller;2  3 ImportJavax.validation.Valid;4 ImportOrg.springframework.stereotype.Controller;5 ImportOrg.springframework.ui.ModelMap;6 ImportOrg.springframework.validation.BindingResult;7 Importorg.springframework.web.bind.annotation.RequestMapping;8 ImportOrg.springframework.web.bind.annotation.RequestMethod;9 ImportCom.mkyong.common.model.Customer;Ten   One @Controller A@RequestMapping ("/customer") -  Public classSignupcontroller { -   the@RequestMapping (value = "/signup", method =requestmethod.post) -      PublicString Addcustomer (@Valid customer customer, bindingresult result) { -   -         if(Result.haserrors ()) { +             return"Signupform"; -}Else { +             return"Done"; A         } at   -     } -   -@RequestMapping (method =requestmethod.get) -      PublicString Displaycustomerform (Modelmap model) { -   inModel.addattribute ("Customer",NewCustomer ()); -         return"Signupform"; to   +     } -   the}
1<%@ taglib prefix= "form" uri= "Http://www.springframework.org/tags/form"%>234<style>5 . Error {6 color: #ff0000;7 }8  9 . Errorblock {TenColor: #000; Onebackground-color: #ffEEEE; A border:3px solid #ff0000; - padding:8px; - margin:16px; the } -</style> - -   +<body> - +   A<form:form method= "POST" commandname= "Customer" action= "Customer/signup" > at<form:errors path= "*" cssclass= "errorblock" element= "div"/> -<table> -<tr> -<td>customer Name:</td> -<td><form:input path= "Name"/></td> -<td><form:errors path= "name" cssclass= "Error"/></td> in</tr> -<tr> to<td>customer Age:</td> +<td><form:input path= "Age"/></td> -<td><form:errors path= "Age" cssclass= "error"/></td> the</tr> *<tr> $&LT;TD colspan= "3" ><input type= "Submit"/></td>Panax Notoginseng</tr> -</table> the</form:form> +   A</body> the

You can override the error prompt defined on a persisted object by defining a "validatemessage.properties" file, usually in the form of a property key in the properties file "@Annotation Name.object.fieldname":

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

Code Run Demo:

Springmvc-bean-validation-jsr303-example-2.zip

5. Reference

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

Spring Validation (using Hibernate Validator)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.