Validation framework hibernate validator

step one
import jar package
		<dependency>
		    <groupId>org.hibernate</groupId>
		    <artifactId>hibernate-validator</artifactId>
		    <version>4.3.1.Final</version>
		</dependency>

The second step is to configure the validator

<mvc:annotation-driven  validator="validator"></mvc:annotation-driven>
   	<bean id="validator"  
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">  
      <!-- validator-->   
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />  
        <property name="validationMessageSource" ref="messageSource" />  
    </bean>  
<!-- Verify error message configuration file-->
    <bean id="messageSource"  
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
<!-- resource filename-->
        <property name="basenames">     
            <list>      
            <value>classpath:CustomValidationMessages</value>  
            </list>     
        </property>  
<!-- Resource file encoding format-->
        <property name="fileEncodings" value="utf-8" />  
 <!-- Cache time for resource file content, in seconds-->
        <property name="cacheSeconds" value="120" />  
    </bean>


The third step is to write the content of the prompt information file
user.name.length.error=Username length is not suitable
user.num.noNull=Username cannot be empty

The fourth step is to set the validation rules on the attributes in the entity class
@Size(min=1,max=14,message="{user.name.length.error}")
	@NotEmpty
	private  String userName;

The fifth step is to apply the verification to the instance of the entity class and accept the verification information
@RequestMapping(value="add")
	public void add(HttpServletRequest request,HttpServletResponse response,@Valid User user, BindingResult bindingResult) {
		List<ObjectError> allErrors = bindingResult.getAllErrors();  
	   for(ObjectError e : allErrors){   
				System.out.println(e.getDefaultMessage());
	   }  
	}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325894330&siteId=291194637