springmvc 註解開發之 validation校驗
阿新 • • 發佈:2018-11-10
專案中使用較多的是前端的校驗,比如頁面中js校驗。對於安全要求較高的建議在服務端進行校驗。
服務端校驗:
控制層controller:校驗頁面請求的引數的合法性,在服務端控制層controller校驗,不區分客戶端型別(瀏覽器、手機客戶端、遠端呼叫)
業務層service:主要校驗關鍵業務引數,僅限於service介面中使用的引數
持久層dao:一般是不校驗的。
springmvc校驗
springmvc使用hibernate的校驗框架validation(和hibernate沒有任何關係)
校驗思路:
頁面提交請求的引數,請求controller方法中,使用validation進行校驗。
如果校驗出錯,將錯誤資訊展示到頁面。
validation所需依賴
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.validator.version}</version>
</dependency>
配置校驗器
<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> <!-- 在web環境中一定要定位到classpath 否則預設到當前web應用下找 --> <value>classpath:messages</value> </list> </property> <property name="useCodeAsDefaultMessage" value="false" /> <!--資原始檔編碼格式--> <property name="defaultEncoding" value="UTF-8" /> <!--對資原始檔內容快取時間,單位秒--> <property name="cacheSeconds" value="60" /> </bean>
新增校驗器到處理器介面卡中
<mvc:annotation-driven conversion-service="conversionService"
validator="validator"></mvc:annotation-driven>
在pojo中新增校驗規則
@Size(min = 1,max=30,message="{item.error}")
private Integer id;
@NotNull(message = "{item.isNull}")
private String reviewId;
//messages配置校驗錯誤資訊
item.error=請輸入1到30個字元
item.isNull=不能為空
校驗方法
在controller中實現
//在需要校驗的pojo前加@Validated,在需要校驗的pojo後面新增BindingResult bindingResult結束校驗出錯資訊
//@Validated和BindingResult bindingResult是配對出現,並且順序固定一前一後
@RequestMapping("/queryItems")
public String queryitems(Model model, @Validated ItemsCustom itemsCustom,
BindingResult bindingResult)throws Exception{
//獲取校驗資訊
if(bindingResult.hasErrors()){
//輸出錯誤資訊
List<ObjectError> allErrors = bindingResult.getAllErrors();
for (ObjectError objectError :
allErrors) {
System.out.println(objectError.getDefaultMessage());
}
//將錯誤資訊傳到頁面
model.addAttribute("allErrors",allErrors);
//出錯重新到商品修改頁面
return "items/editItems";
}
//....一系列操作
}
這種方法有一個問題,在pojo中定義校驗規則,而pojo是被多個controller所共用,當不同的controller方法對同一個pojo進行校驗,但是每個controller方法需要不同的校驗。
這時候就需要用到
分組校驗
第一步:建立校驗分組
public interface ValidGroup1{
//介面中不需要定義任何方法,僅是對不同的校驗規則進行分組
//此分組只校驗商品名稱長度
}
第二步:新增分組
//group:此校驗屬於哪個分組,可新增多個
@Size(min = 1,max=30,message="{item.error}",groups = {ValidGroup1.class})
第三步:在controller中指定分組
//value = {ValidGroup1.class}指定使用ValidGroup1分組的校驗
@RequestMapping("/queryItems")
public String queryitems(Model model, @Validated(value = {ValidGroup1.class})ItemsCustom itemsCustom, BindingResult bindingResult)throws Exception{