Hibernate Validator Useimport Validation-api-xxx.jar and hibernate-validator-xxx. Final.jarJava Bean Entity.java to check
Import Javax.validation.constraints.max;import Org.hibernate.validator.constraints.length;public class Entity {@Max (value=3)//maximum value is 3private int age; @Length (max=1)///String length maximum is 1,hibernate extended private string name;public int getage () {return Age;} public void Setage (int.) {this.age = age;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}}
Test class for value validation
Import Java.util.set;import Javax.validation.constraintviolation;import Javax.validation.validation;import Javax.validation.validator;import Javax.validation.validatorfactory;public class Tv {public static void main (string[] args) {Validatorfactory factory = Validation.builddefaultvalidatorfactory (); Validator Validator = Factory.getvalidator (); Entity entity = new entity (); Entity.setage (n); Entity.setname ("admin"); set<constraintviolation<entity>> constraintviolations = validator.validate (Entity); Constraintviolation<entity> constraintviolation:constraintviolations) {System.out.println ("Object properties:" + Constraintviolation.getpropertypath ()); System.out.println ("Internationalized Key:" +constraintviolation.getmessagetemplate ()); SYSTEM.OUT.PRINTLN ("error message:" +constraintviolation.getmessage ());}}}
Output results
There is an internationalized key value, internationalized file in a series of properites files below Org.hibernate.validator, if need to customize then can be copied out and placed in the SRC directory
Here we copy one out, add a key to maxlength= string length maximum cannot exceed {max}, you can use dynamic parameters, where the max value is the value set in the annotation and then modify the Entity.java,name property message= "{ MaxLength} "
@Length (max=1,message= "{maxlength}")//{maxlength} corresponds to key in the configuration file. Must have {}private String name;
Run the results again as follows
Custom ValidatorFirst, customize an annotation cannotcontainspaces (cannot contain spaces)
Import Java.lang.annotation.documented;import Java.lang.annotation.retention;import java.lang.annotation.Target; Import Javax.validation.constraint;import javax.validation.Payload; @Constraint (Validatedby = Cannotcontainspacesvalidator.class)//Specific implementation @target ({Java.lang.annotation.ElementType.METHOD, Java.lang.annotation.ElementType.FIELD}) @Retention (Java.lang.annotation.RetentionPolicy.RUNTIME) @ Documentedpublic @interface cannotcontainspaces {String message () default "{Cannot.contain.Spaces}";//Prompt message, can write dead, You can fill in the internationalized keyint length () default 5;//the following two properties must be added class<?>[] groups () default {}; class<? Extends payload>[] Payload () default {};}
Concrete Implementation Class Cannotcontainspacesvalidator.java
Import Javax.validation.constraintvalidator;import Javax.validation.constraintvalidatorcontext;public class Cannotcontainspacesvalidator implements Constraintvalidator<cannotcontainspaces, string> {private int len;/** * Initial parameter, gets the value of length in the callout */@Overridepublic void Initialize (Cannotcontainspaces arg0) {This.len = Arg0.length ();} @Overridepublic boolean isValid (String str, constraintvalidatorcontext constraintvalidatorcontext) {if (str! = null) {if (Str.indexof ("") < 0) {return true;}} Else{constraintvalidatorcontext.disabledefaultconstraintviolation ();//Disable the value of the default message// Re-add the error prompt statement Constraintvalidatorcontext . Buildconstraintviolationwithtemplate ("String cannot be empty"). Addconstraintviolation ();} return false;}}
It is possible to annotate directly to the object's properties when using it.
@CannotContainSpacesprivate String name;
Test when name contains a space entity.setname ("xx xx");
When name is null
Integrate spring MVCFirst add the configuration file content (the annotation inside the entity class is exactly the same as above)
<!--internationalization configuration--><bean id= "Localeresolver" class= " Org.springframework.web.servlet.i18n.CookieLocaleResolver "/><bean id=" Messagesource "class=" Org.springframework.context.support.ReloadableResourceBundleMessageSource "><property name=" Basenames "> <list><value>classpath:messages/messages</value><value>classpath:messages/validation </value></list></property><property name= "Usecodeasdefaultmessage" value= "true"/></ bean><!--Registration Authenticator--><mvc:annotation-driven validator= "validator"/> <bean id= "Validator" class= " Org.springframework.validation.beanvalidation.LocalValidatorFactoryBean "> <property name=" Providerclass "va Lue= "Org.hibernate.validator.HibernateValidator"/> <!--here configuration will use the above internationalized configuration Messagesource--<proper Ty name= "Validationmessagesource" ref= "Messagesource"/> </bean>
The method properties in the Spring MVC controller are as follows
/** * Here the @valid must be written, Bindingresult parameters must also be written in the back, otherwise the validation will return to the @param entity * @param result * @return */@RequestMapping (VA Lue= "/valid") Public String Validator (@Valid Entity entity,bindingresult result) {if (Result.haserrors ()) {///If the severity does not pass, Jump prompt return "error";} else{//Continue business logic}return "Success";}
Error.jsp in the followingImport Spring Tag library
<%@ taglib uri= "http://www.springframework.org/tags/form" prefix= "form"%>
<!--the object name in the CommandName controller parameter--><form:form commandname= "entity" ><!--Show all error messages with *--><form:errors Path= "*"/></form:form>
Validation Note Description
The built-in constraint in Bean Validation @Null The annotated element must be null @NotNull The annotated element must not be null @AssertTrue The annotated element must be true @AssertFalse the annotated element must be false @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 annotated element 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 @Future 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 =) The validation string is non-null and must be longer than 0 @Email the annotated element must be an e-mail address @Length (min=,max=) The size of the commented 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
Note①: When integrating spring MVC, the validationmessages_zh_cn.properties file is not placed in the SRC directory (as above under src/messages/) You cannot use dynamic parameters in the properties file (such as ${length} ${max}). You must place all the internationalized properties of hibernate validation under the SRC directory (don't know why, if you can fix it by leaving a message)
②: I am using Spring 4.1 + Hibernate validation 5.1, if you are using Spring 3.2 need for the Hibernate validation version is 4.x otherwise in the configurationOrg.springframework.validation.beanvalidation.LocalValidatorFactoryBean
This is going to be an error,
Hibernate validator using and customizing validator and integrating Spring MVC