springMVC学习(7)-springMVC校验
一、校驗(yàn)理解:
對(duì)于安全要求較高點(diǎn)建議在服務(wù)端進(jìn)行校驗(yàn)。
控制層conroller:校驗(yàn)頁(yè)面請(qǐng)求的參數(shù)的合法性。在服務(wù)端控制層conroller校驗(yàn),不區(qū)分客戶端類(lèi)型(瀏覽器、手機(jī)客戶端、遠(yuǎn)程調(diào)用)
業(yè)務(wù)層service(使用較多):主要校驗(yàn)關(guān)鍵業(yè)務(wù)參數(shù),僅限于service接口中使用的參數(shù)。
持久層dao:一般是不校驗(yàn)
二、SpringMVC校驗(yàn)需求:
springmvc使用hibernate的校驗(yàn)框架validation(和hibernate沒(méi)有任何關(guān)系)。
思路:
頁(yè)面提交請(qǐng)求的參數(shù),請(qǐng)求到controller方法中,使用validation進(jìn)行校驗(yàn)。如果校驗(yàn)出錯(cuò),將錯(cuò)誤信息展示到頁(yè)面。
具體需求:
商品修改,添加校驗(yàn)(校驗(yàn)商品名稱(chēng)長(zhǎng)度,生產(chǎn)日期的非空校驗(yàn))如果校驗(yàn)出錯(cuò),在商品修改頁(yè)面顯示錯(cuò)誤信息。
三、環(huán)境準(zhǔn)備:
添加jar包:這里使用的是:
hibernate-validator-4.3.0-Final.jar;
jboss-logging-3.1.0.CR2.jar;
validation-api-1.0.0.GA.jar;
四、相關(guān)配置:
1)配置校驗(yàn)器:
1 <mvc:annotation-driven conversion-service="conversionService" validator="validator"> 2 </mvc:annotation-driven> 3 <!-- 校驗(yàn)器 --> 4 <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> 5 <!-- hibernate校驗(yàn)器--> 6 <property name="providerClass" value="org.hibernate.validator.HibernateValidator" /> 7 <!-- 指定校驗(yàn)使用的資源文件,在文件中配置校驗(yàn)錯(cuò)誤信息,如果不指定則默認(rèn)使用classpath下的ValidationMessages.properties --> 8 <property name="validationMessageSource" ref="messageSource" /> 9 </bean> 10 <!-- 校驗(yàn)錯(cuò)誤信息配置文件 --> 11 <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 12 <!-- 資源文件名--> 13 <property name="basenames"> 14 <list> 15 <value>classpath:CustomValidationMessages</value> 16 </list> 17 </property> 18 <!-- 資源文件編碼格式 --> 19 <property name="fileEncodings" value="utf-8" /> 20 <!-- 對(duì)資源文件內(nèi)容緩存時(shí)間,單位秒 --> 21 <property name="cacheSeconds" value="120" /> 22 </bean>2)由于這里是在Contoller中的形參(ItemsCustom)來(lái)接收參數(shù),在pojo中添加校驗(yàn)規(guī)則:
1 public class Items { 2 private Integer id; 3 4 //校驗(yàn)名稱(chēng)在1到30字符中間 5 //message是提示校驗(yàn)出錯(cuò)顯示的信息 6 @Size(min=1,max=30,message="{items.name.length.error}") 7 private String name; 8 private Float price; 9 private String pic; 10 11 //非空校驗(yàn) 12 @NotNull(message="{items.createtime.isNUll}") 13 private Date createtime; 14 15 .... 16 } View Code3)配置校驗(yàn)錯(cuò)誤提示信息文件 --?/springMVC/config/CustomValidationMessages.properties
#items modify error message items.name.length.error=the item name must be between 1-30 char items.createtime.isNUll=the createtime should be not null View Code4)在controller中編寫(xiě)校驗(yàn)、捕獲校驗(yàn)錯(cuò)誤信息:
1 //商品信息修改提交 2 // 在需要校驗(yàn)的pojo前邊添加@Validated,在需要校驗(yàn)的pojo后邊添加BindingResult 3 // bindingResult接收校驗(yàn)出錯(cuò)信息 4 // 注意:@Validated和BindingResult bindingResult是配對(duì)出現(xiàn),并且形參順序是固定的(一前一后)。 5 @RequestMapping("/editItemsSubmit") 6 public String editItemsSubmit(Model model, 7 HttpServletRequest request, 8 Integer id, 9 @Validated ItemsCustom itemsCustom,BindingResult bindingResult) 10 throws Exception { 11 12 if(bindingResult.hasErrors()){ 13 List<ObjectError> allErrors = bindingResult.getAllErrors(); 14 for(ObjectError objectError : allErrors){ 15 System.out.println(objectError.getDefaultMessage()); 16 } 17 18 // 將錯(cuò)誤信息傳到頁(yè)面 19 model.addAttribute("allErrors", allErrors); 20 21 return "items/editItems"; 22 } 23 24 itemsService.updateItems(id, itemsCustom); 25 return "success"; 26 } View Code5)jsp頁(yè)面展示錯(cuò)誤信息:
1 <!-- 顯示錯(cuò)誤信息 --> 2 <c:if test="${allErrors!=null}"> 3 錯(cuò)誤信息:<br/> 4 <c:forEach items="${allErrors}" var="error"> 5 ${error.defaultMessage}<br/> 6 </c:forEach> 7 </c:if> View Code效果:后臺(tái)打印:
前臺(tái)展示:
?
?
---------------------------------------------------------------------------------------------------------------------------------------
?分組校驗(yàn):
需求:
在pojo中定義校驗(yàn)規(guī)則,而pojo是被多個(gè) controller所共用,當(dāng)不同的controller方法對(duì)同一個(gè)pojo進(jìn)行校驗(yàn),但是每個(gè)controller方法需要不同的校驗(yàn)。
解決辦法:
定義多個(gè)校驗(yàn)分組(其實(shí)是一個(gè)java接口),分組中定義有哪些規(guī)則
每個(gè)controller方法使用不同的校驗(yàn)分組
1)定義兩個(gè)校驗(yàn)分組:
package com.cy.controller.validation;/*** 校驗(yàn)分組* @author chengyu**/ public interface ValidGroup1 {//接口中不需要定義任何方法,僅是對(duì)不同的校驗(yàn)規(guī)則進(jìn)行分組//此分組只校驗(yàn)商品名稱(chēng)長(zhǎng)度 }....public interface ValidGroup2 {} View Code2)在校驗(yàn)規(guī)則中添加分組,Items中:
1 public class Items { 2 private Integer id; 3 4 //校驗(yàn)名稱(chēng)在1到30字符中間 5 //message是提示校驗(yàn)出錯(cuò)顯示的信息 6 //groups:此校驗(yàn)屬于哪個(gè)分組,groups可以定義多個(gè)分組 7 @Size(min=1,max=30,message="{items.name.length.error}",groups={ValidGroup1.class}) 8 private String name; 9 private Float price; 10 private String pic; 11 12 //非空校驗(yàn) 13 @NotNull(message="{items.createtime.isNUll}") 14 private Date createtime; 15 16 ..... 17 18 } View Code3)在Controller方法中指定分組的校驗(yàn):
1 //商品信息修改提交 2 // 在需要校驗(yàn)的pojo前邊添加@Validated,在需要校驗(yàn)的pojo后邊添加BindingResult 3 // bindingResult接收校驗(yàn)出錯(cuò)信息 4 // 注意:@Validated和BindingResult bindingResult是配對(duì)出現(xiàn),并且形參順序是固定的(一前一后)。 5 // value={ValidGroup1.class}指定使用ValidGroup1分組的 校驗(yàn) 6 @RequestMapping("/editItemsSubmit") 7 public String editItemsSubmit(Model model, 8 HttpServletRequest request, 9 Integer id, 10 @Validated(value={ValidGroup1.class}) ItemsCustom itemsCustom,BindingResult bindingResult) 11 throws Exception { 12 13 if(bindingResult.hasErrors()){ 14 List<ObjectError> allErrors = bindingResult.getAllErrors(); 15 for(ObjectError objectError : allErrors){ 16 System.out.println(objectError.getDefaultMessage()); 17 } 18 19 // 將錯(cuò)誤信息傳到頁(yè)面 20 model.addAttribute("allErrors", allErrors); 21 22 return "items/editItems"; 23 } 24 25 itemsService.updateItems(id, itemsCustom); 26 return "success"; 27 } View Code后臺(tái)打印:
前臺(tái)頁(yè)面:
轉(zhuǎn)載于:https://www.cnblogs.com/tenWood/p/6312535.html
總結(jié)
以上是生活随笔為你收集整理的springMVC学习(7)-springMVC校验的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: JavaScript数据类型 typeo
- 下一篇: springMVC一些实践总结