Hibernate Validation Verification

Source: Internet
Author: User
Tags min regular expression valid

First, preface


Hibernate validation is a back-end validation framework that is currently a popular validation practice: Front end jquery-form-validate + backend hibernate-validate, which mentions hibernate Validator has to mention the JSR 303-bean Validation specification, JSR-303 is a sub-specification in Java EE 6, called the Bean Validation, the official reference implementation is Hibernate Validator, This implementation has nothing to do with Hibernate ORM, and JSR 303 is used to validate the values of fields in Java beans, providing implementations of all the built-in constraint in the JSR 303 specification, plus some additional constraint.


second, hibernate Validation constraint annotation


2.1. Constraint (constraint) built into Bean Validation


@Null The annotated element must be Null
@NotNull 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

2.2. Hibernate Validator Additional constraint


@NotBlank (message =) validation string is not null and must be longer 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


Hibernate supplemental Annotations, the last 3 are not commonly used, can be ignored.


The difference between the @notnull @NotEmpty @NotBlank 3 annotations is mainly distinguished:


@NotNull value of any object cannot be null
The elements of the @NotEmpty collection object are not 0, that is, the collection is not empty, or it can be used for strings that are NOT null
@NotBlank can only be used for strings that are not null, and the string trim () after length is greater than 0


third, the use


Hibernate validation is very simple to use, just add annotations to the corresponding entity classes, and then call the corresponding validation API method.


A) configuration Validator


There are several ways to configure the spring configuration file first:


1. After spring3, any Validator that support JSR303 (such as Hibernate Validator) can be introduced with simple configuration, simply by adding in the configuration XML, At this point the Validatemessage property file defaults to Validationmessages.properties under Classpath:

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

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

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

<bean id= "Validator" class= " Org.springframework.validation.beanvalidation.LocalValidatorFactoryBean ">
    <property name=" Providerclass "  value=" Org.hibernate.validator.HibernateValidator "/>
    <!-- Do not set the default is Classpath under 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= "/>"  


B) Configuring validator validation rules


Package com.fendo.pays.request;

Import Java.util.Date;
Import Javax.validation.constraints.Min;
Import Javax.validation.constraints.NotNull;
Import Javax.validation.constraints.Pattern;

Import javax.validation.constraints.Size;
Import Org.hibernate.validator.constraints.Email;
Import Org.hibernate.validator.constraints.NotBlank;
Import Org.hibernate.validator.constraints.NotEmpty;

Import Org.springframework.format.annotation.DateTimeFormat; /** * @Title: Userrequest.java * @Package com.fendo.pays.request * @Description: User Request Parameters * @author Fendo * @date  October 2, 2017 pm 11:36:17 * @version V1.0 */public class Userrequest {private String ID;  Uniquely identifies @Size (min=1,max=30,message= "{user.name.length.error}") private String name; Name @NotBlank (message= "{user.password.isNull}") @Pattern (regexp= "^ (?! [0-9]+$) (?! [a-za-z]+$] [0-9a-za-z]{6,10}$], message= "{user.password.error}") private String password; Password private String Idcard; Bank card number @NotBlank (message= "{User.emAil.isnull} ") @Email (message=" {user.email.error} ") Private String Email;  Mailbox @NotEmpty (message= "{user.addres.isNull}") Private String addres; Address @Pattern (regexp= "^ (13[0-9) | ( 15[^4,\\D]) | (18[0,5-9])) \\d{8}$ ", message=" {user.mobile.error} ") Private String mobile;
	Mobile number @NotNull (message= "{user.highbloodpressure.isNull}") @Min (value=1,message= "{user.highbloodpressure.error}")  Private Double highbloodpressure; High blood pressure @NotNull (message= "{User. Lowbloodpressure.isnull} ") @Min (value=1,message=" {User. Lowbloodpressure.error} ") Private Double lowbloodpressure; Low blood pressure private Integer idcardnum; Number of bank cards @DateTimeFormat (pattern= "Yyyy-mm-dd") @NotNull (message= "{user.createtime.isNull}") Private Date createtime;/
 /Date of Creation ...}

Create a new validationmessages.properties configuration file in the resource directory with the following contents:

#配置错误提示信息
user.name.length.error= Please enter a product name of 1 to 30 characters
user.createtime.isnull= Please enter the product date
of production user.email.error= Please enter the correct mailbox
user.email.isnull= mailbox cannot be empty
user.mobile.error= Please enter the correct phone number
user.password.isnull= Please enter the password
user.password.error= password must be a combination of 6~10 digits and letters
user.highbloodpressure.isnull= High blood pressure cannot be empty
user.highbloodpressure.error= the value of high blood pressure is at least 1
user. Lowbloodpressure.isnull= blood pressure cannot be empty
user. Lowbloodpressure.error= high blood pressure is at least 1
user.addres.isnull= address cannot be empty

Use the {User.createtime.isNull} method directly in the entity class to get it:



C) Use of validator


There are several ways to use validator in spring:


1. Add the @valid annotation (which is in the Javax.validation package) to trigger the checksum before the object that needs verification. 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.


@RequestMapping (value = "/addusers", method = Requestmethod.get) @ResponseBody public simpleresult addusers (@Valid Userrequest Userrequest,bindingresult Bindingresult) throws Exception {Simpleresult SIMPLERESULT=SIMPLERESULT.SUCC
       ESS ();
		 
       Logger.info ("[/user/addusers]"); Gets the checksum error message if (Bindingresult.haserrors ()) {//Output error message list<fielderror> allerrors = Bindingresult.getfiel
	     Derrors ();
		for (Fielderror objecterror:allerrors) {System.out.println (Objecterror.getdefaultmessage ());
	        Upload error message to page//simpleresult.put (Objecterror.getfield (), Objecterror.getdefaultmessage ());
	      Return Simpleresult.error (SimpleCode.ERROR.getCode (), Objecterror.getdefaultmessage ());
         }} System.out.println (Userrequest.tostring ());   Use the Date Converter tool class Convertutils.register (new Datelocaleconverter (), date.class);
		 Not flexible, to achieve their own best userentity userentity=new userentity ();
		 Beanutils.copyproperties (Userrequest, userentity); Userentity.sEtid (Uuidtool.getuuid ());
		 Userservice.insertuser (userentity);
		 
	 return simpleresult; }


Or use @validated annotations, all the same:

@RequestMapping (value = "/adduser", method = Requestmethod.get) @ResponseBody @SystemControllerLog (modelname= " Usercontroller ", option=" AddUser ", description =" New user ") public simpleresult AddUser (model, @Validated userrequest

	 Userrequest,bindingresult Bindingresult) throws Exception {Simpleresult simpleresult=simpleresult.success ();
	 
	 Logger.info ("[/user/adduser]"); Gets the checksum error message if (Bindingresult.haserrors ()) {//Output error message list<fielderror> allerrors = bindingresult.getfielderrors
		();
			for (Fielderror objecterror:allerrors) {System.out.println (Objecterror.getdefaultmessage ());
			 Upload error message to page//simpleresult.put (Objecterror.getfield (), Objecterror.getdefaultmessage ());

		Return Simpleresult.error (SimpleCode.ERROR.getCode (), Objecterror.getdefaultmessage ());
 
		 }} System.out.println (Userrequest.tostring ());   Use the Date Converter tool class Convertutils.register (new Datelocaleconverter (), date.class);
	 Not flexible, to achieve their own best userentity userentity=new userentity (); BeanuTils.copyproperties (Userrequest, userentity);
	 Userentity.setid (Uuidtool.getuuid ());
	 Userservice.insertuser (userentity);
 
return simpleresult; }

2. Verify by Spring Injection validator:


@Autowired
private Validator Validator;


@RequestMapping (value = "/adduseres", method = Requestmethod.get)
@ResponseBody
@SystemControllerLog ( Modelname= "Usercontroller", option= "AddUser", description = "New user") public 
Simpleresult Adduseres (userrequest Userrequest) throws Exception {
	 simpleresult simpleresult=simpleresult.success ();
	 Logger.info ("[/user/adduseres]");
	 
	 if (Validates (validator, userrequest)!=null) {
		 return Simpleresult.error (SimpleCode.ERROR.getCode (), Validates ( Validator, userrequest));
	 }
	 System.out.println (Userrequest.tostring ());
	 Use the Date Converter tool class
	 //convertutils.register (New Datelocaleconverter (), date.class);   Not flexible, to achieve their own best
	 userentity userentity=new userentity ();
	 Beanutils.copyproperties (Userrequest, userentity);
	 Beanutilsexs.copyproperties (Userrequest, userentity);
	 Userentity.setid (Uuidtool.getuuid ());
	 Userservice.insertuser (userentity);
	 return simpleresult;
}


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.