1. 程式人生 > >SpringMVC伺服器端校驗-有配置檔案

SpringMVC伺服器端校驗-有配置檔案

Hibernate-validator進行驗證

配置beans.xml檔案,如下:

複製程式碼
<!-- 預設的註解對映的支援 -->  
    <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>
複製程式碼

其中<property name="basename" value="classpath:validatemessages"/>中的classpath:validatemessages為註解驗證訊息所在的檔案,需要我們在resources資料夾下新增。

在com.demo.web.controllers包中新增一個ValidateController.java內容如下:

複製程式碼
package com.demo.web.controllers;

import java.security.NoSuchAlgorithmException;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.demo.web.models.ValidateModel;

@Controller
@RequestMapping(value = "/validate")
public class ValidateController {
    
    @RequestMapping(value="/test", method = {RequestMethod.GET})
    public String test(Model model){

        if(!model.containsAttribute("contentModel")){
            model.addAttribute("contentModel", new ValidateModel());
        }
        return "validatetest";
    }
    
    @RequestMapping(value="/test", method = {RequestMethod.POST})
    public String test(Model model, @Valid @ModelAttribute("contentModel") ValidateModel validateModel, BindingResult result) throws NoSuchAlgorithmException{
        
        //如果有驗證錯誤 返回到form頁面
        if(result.hasErrors())
            return test(model);
        return "validatesuccess";     
    }
    
}
複製程式碼

其中@Valid @ModelAttribute("contentModel") ValidateModel validateModel的@Valid 意思是在把資料繫結到@ModelAttribute("contentModel") 後就進行驗證。

在com.demo.web.models包中新增一個ValidateModel.java內容如下:

複製程式碼
package com.demo.web.models;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;

public class ValidateModel{
    
    @NotEmpty(message="{name.not.empty}")
    private String name;
    @Range(min=0, max=150,message="{age.not.inrange}")
    private String age;
    @NotEmpty(message="{email.not.empty}")
    @Email(message="{email.not.correct}")
    private String email;
    
    public void setName(String name){
        this.name=name;
    }
    public void setAge(String age){
        this.age=age;
    }
    public void setEmail(String email){
        this.email=email;
    }
    
    public String getName(){
        return this.name;
    }
    public String getAge(){
        return this.age;
    }
    public String getEmail(){
        return this.email;
    }
    
}
複製程式碼

在註解驗證訊息所在的檔案即validatemessages.properties檔案中新增以下內容:

name.not.empty=\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A\u3002
age.not.inrange=\u5E74\u9F84\u8D85\u51FA\u8303\u56F4\u3002
email.not.correct=\u90AE\u7BB1\u5730\u5740\u4E0D\u6B63\u786E\u3002
email.not.empty=\u7535\u5B50\u90AE\u4EF6\u4E0D\u80FD\u60DF\u6050\u3002

其中name.not.empty等分別對應了ValidateModel.java檔案中message=”xxx”中的xxx名稱,後面的內容是在輸入中文是自動轉換的ASCII編碼,當然你也可以直接把xxx寫成提示內容,而不用另建一個validatemessages.properties檔案再新增,但這是不正確的做法,因為這樣硬編碼的話就沒有辦法進行國際化了。

下面是主要的驗證註解及說明:

註解

適用的資料型別

說明

@AssertFalse

Boolean, boolean

驗證註解的元素值是false

@AssertTrue

Boolean, boolean

驗證註解的元素值是true

@DecimalMax(value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

驗證註解的元素值小於等於@ DecimalMax指定的value值

@DecimalMin(value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

驗證註解的元素值小於等於@ DecimalMin指定的value值

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

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

驗證註解的元素值的整數位數和小數位數上限

@Future

java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

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

@Max(value=x)

BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type ofCharSequence (the numeric value represented by the character sequence is evaluated), any sub-type of Number.

驗證註解的元素值小於等於@Max指定的value值

@Min(value=x)

BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of CharSequence (the numeric value represented by the char sequence is evaluated), any sub-type of Number.

驗證註解的元素值大於等於@Min指定的value值

@NotNull

Any type

驗證註解的元素值不是null

@Null

Any type

驗證註解的元素值是null

@Past

java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

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

@Pattern(regex=正則表示式, flag=)

String. Additionally supported by HV: any sub-type of CharSequence.

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

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

String, Collection, Map and arrays. Additionally supported by HV: any sub-type of CharSequence.

驗證註解的元素值的在min和max(包含)指定區間之內,如字元長度、集合大小

@Valid

Any non-primitive type(引用型別)

驗證關聯的物件,如賬戶物件裡有一個訂單物件,指定驗證訂單物件

@NotEmpty

CharSequence,CollectionMap and Arrays

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

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

CharSequence, Collection, Map and Arrays,BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types

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

@NotBlank

CharSequence

驗證註解的元素值不為空(不為null、去除首位空格後長度為0),不同於@NotEmpty,@NotBlank只應用於字串且在比較時會去除字串的空格

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

CharSequence

驗證註解的元素值長度在min和max區間內

@Email

CharSequence

驗證註解的元素值是Email,也可以通過正則表示式和flag指定自定義的email格式