欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用Spring注入Hibernate驗證框架

 更新時間:2021年12月02日 14:45:20   作者:clypm  
這篇文章主要介紹了使用Spring注入Hibernate驗證框架方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

Spring注入Hibernate驗證框架

Spring配置文件

<!-- Enables the Spring MVC @Controller programming model -->
 <mvc:annotation-driven validator="validator" />
 
 <!-- 配置數(shù)據(jù)校驗 -->
 <bean id="messageSource"
  class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
        <property name="basename" value="classpath:messages"/>
        <property name="fileEncodings" value="utf-8"/>
        <property name="cacheSeconds" value="10"/>
 </bean>
 <bean id="validator"
  class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">  
        <property name="providerClass"
   value="org.hibernate.validator.HibernateValidator"/>
  <property name="validationMessageSource" ref="messageSource"/>
 </bean>

Hibernate內(nèi)置的驗證約束注解如下表所示

(摘自hibernate validator reference):

驗證注解

驗證的數(shù)據(jù)類型

說明

@AssertFalse

Boolean,boolean

驗證注解的元素值是false

@AssertTrue

Boolean,boolean

驗證注解的元素值是true

@NotNull

任意類型

驗證注解的元素值不是null

@Null

任意類型

驗證注解的元素值是null

@Min(value=值)

BigDecimal,BigInteger, byte,

short, int, long,等任何Number或CharSequence(存儲的是數(shù)字)子類型

驗證注解的元素值大于等于@Min指定的value值

@Max(value=值)

和@Min要求一樣

驗證注解的元素值小于等于@Max指定的value值

@DecimalMin(value=值)

和@Min要求一樣

驗證注解的元素值大于等于@ DecimalMin指定的value值

@DecimalMax(value=值)

和@Min要求一樣

驗證注解的元素值小于等于@ DecimalMax指定的value值

@Digits(integer=整數(shù)位數(shù), fraction=小數(shù)位數(shù))

和@Min要求一樣

驗證注解的元素值的整數(shù)位數(shù)和小數(shù)位數(shù)上限

@Size(min=下限, max=上限)

字符串、Collection、Map、數(shù)組等

驗證注解的元素值的在min和max(包含)指定區(qū)間之內(nèi),如字符長度、集合大小

@Past

java.util.Date,

java.util.Calendar;

Joda Time類庫的日期類型

驗證注解的元素值(日期類型)比當前時間早

@Future

與@Past要求一樣

驗證注解的元素值(日期類型)比當前時間晚

@NotBlank

CharSequence子類型

驗證注解的元素值不為空(不為null、去除首位空格后長度為0),不同于@NotEmpty,@NotBlank只應(yīng)用于字符串且在比較時會去除字符串的首位空格

@Length(min=下限, max=上限)

CharSequence子類型

驗證注解的元素值長度在min和max區(qū)間內(nèi)

@NotEmpty

CharSequence子類型、Collection、Map、數(shù)組

驗證注解的元素值不為null且不為空(字符串長度不為0、集合大小不為0)

@Range(min=最小值, max=最大值)

BigDecimal,BigInteger,CharSequence, byte, short, int, long等原子類型和包裝類型

驗證注解的元素值在最小值和最大值之間

@Email(regexp=正則表達式,

flag=標志的模式)

CharSequence子類型(如String)

驗證注解的元素值是Email,也可以通過regexp和flag指定自定義的email格式

@Pattern(regexp=正則表達式,

flag=標志的模式)

String,任何CharSequence的子類型

驗證注解的元素值與指定的正則表達式匹配

@Valid

任何非原子類型

指定遞歸驗證關(guān)聯(lián)的對象;

如用戶對象中有個地址對象屬性,如果想在驗證用戶對象時一起驗證地址對象的話,在地址對象上加@Valid注解即可級聯(lián)驗證

springmvc使用Hibernate的校驗框架validation

一、Hibernate中的validator需要的jar包

  • hibernate-validator-4.3.1.Final.jar
  • jboss-logging-3.1.0.GA.jar
  • validation-api-1.1.0.Final.jar

二、配置校驗器

<!-- 校驗器 -->
    <bean id="validator"
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <!-- 校驗器-->
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
        <!-- 指定校驗使用的資源文件,如果不指定則默認使用classpath下的ValidationMessages.properties -->
        <property name="validationMessageSource" ref="messageSource" />
    </bean>
    <!-- 校驗錯誤信息配置文件 -->
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <!-- 資源文件名-->
        <property name="basenames">   
            <list>    
            <value>classpath:CustomValidationMessages</value>
            </list>   
        </property>
        <!-- 資源文件編碼格式 -->
        <property name="fileEncodings" value="utf-8" />
        <!-- 對資源文件內(nèi)容緩存時間,單位秒 -->
        <property name="cacheSeconds" value="120" />
    </bean>

三、校驗器注冊到處理器適配器中

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

四、在pojo中添加校驗規(guī)則

package acm.user.po; 
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
 
public class User {
    private Integer id; 
    //校驗名字1到30個字符中間
    //message是提示校驗出錯信息
    @Size(min=1, max=30, message="{user.name.length.error}")
    private String name; 
    //非空校驗
    @NotNull(message="{user.num.noNull}")
    private String num; 
    private String sex; 
    private String tel;
            .
            .
            .
            .
    public Integer getId() {
        return id;
    } 
    public void setId(Integer id) {
        this.id = id;
    } 
}

配置文件中的代碼

user.name.length.error=請輸入1到30個字符的名字
user.num.noNull=請輸入商品的生產(chǎn)日期

五、controller測試

@RequestMapping(value = "updateUser")
public String updateUser(@Validated User user, BindingResult bindingResult){
    List<ObjectError> allErrors = bindingResult.getAllErrors();
    //獲得錯誤信息
    for(ObjectError e : allErrors){
        //輸出錯誤信息
        System.out.println(e.getDefaultMessage());   
    }
    try{
        int count = userService.updateUser(user);
    } catch(Exception e){
        e.printStackTrace();
    }
    return "message";
} 

分組校驗

定義多個校驗分組,分組中定義有些規(guī)則

每個controller方法中定義不同的校驗分組

定義一個接口,里面可以不寫東西,用來裝一個分組

在pojo中寫出每一個被校驗的字段屬于哪一個分組

//校驗名字1到30個字符中間
//message是提示校驗出錯信息
//標識此校驗屬于哪個分組,group也可屬于多個分組
@Size(min=1, max=30, message="{user.name.length.error}", groups={Validation1.class})
private String name;

在controller里使用分組校驗

@Validated中的參數(shù)指向那個檢驗分組
@RequestMapping(value = "updateUser")
public String updateUser(@Validated(value={Validation1.class}) User user, BindingResult bindingResult){
    if(bindingResult.hasErrors()){
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        //獲得錯誤信
       for(ObjectError e : allErrors){
            //輸出錯誤信息
            System.out.println(e.getDefaultMessage());
        }
    }
    try{
        int count = userService.updateUser(user);
    } catch(Exception e){
        e.printStackTrace();
    }
    return "message";
}

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論