1. 程式人生 > >利用validation實現spring 表單的資料驗證

利用validation實現spring 表單的資料驗證

     對於表單的驗證一直是個難的問題,看別人的程式碼發現了,可以用alidate jar 與hibernate-alidate jar來實現驗證,可以對錶單資料進行封裝,然後給spring mvc controller上加上@Valid對欄位進行驗證,如何配置:需要validate jar  ,hibernate alidate jar ,jboss-logging jar ,classmate jar需要在springmvc 的配置中加上alidate的配置加上如下內容:

      <mvc:annotation-driven  validator="validator" conversion-service="conversion-service" />
    
    <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="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
    <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>

給要驗證的屬性上加上@NotNull驗證非空,@NotBlank驗證是否為空字串,@Pattern(regexp="^1[3|4|5|7|8]{1}[0-9]{9}$",message="手機號錯誤")正則表示式驗證。

controller上如下:例如:

@RequestMapping("/userget.json")
@ResponseBody
public String getUser(@Valid User user,Errors error){
System.out.println("name="+user.getName()+",phone="+user.getPhone()+";");
    if(error.hasErrors()){
        for(int i=0;i<error.getErrorCount();i++){
        System.out.println("message="+error.getAllErrors().get(i).getDefaultMessage());
        }
        
   return error.getAllErrors().get(0).getDefaultMessage();


   
    } else {
    return null;
    }
}

就這樣搞定了。