SpringMVC框架(2)之(2.3 Validation校驗器)
Validation校驗器
SpringMVC使用 JSR-303 校驗規範,使用是 Hibernate Validator
【1】設定環境:
1.導jar包;
2.在處理器介面卡中配置校驗器;
3.建立資原始檔(eg:CustomValiationMessages.properties);
【2】校驗規則:(POJO類對應的欄位上)
需求:商品提交時校驗
1.商品名稱長度1~30個字元;
2.商品生產日期不能為空;
【3】捕獲錯誤:
需要修改 Controller:
1.在需要校驗的 POJO類前新增 @Validated註解;
2.在需要校驗的 POJO類之後(緊跟)新增引數 BindingResult bindingResult;
【4】在頁面中顯示錯誤資訊:
jsp頁面中遍歷錯誤資訊;
(1. springmvc.xml中處理器介面卡中配置校驗器; 根據<value>classpath:CustomValiationMessages</value>
在 config資料夾下建立 CustomValiationMessages.properties資原始檔; 3.Items.java中分別在欄位上新增 @Size (min=1,max=30,message="{items.name.length.error}")、 @NotNull (message="{items.createtime.is.notnul}")註解,message的值根據 properties檔案中的 key來得到; 在頁面中顯示錯誤資訊:需要在4.ItemsController.java
model.addAttribute("errors",errors);
;)
1. springmvc.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- (開啟spring註解掃描)3.註解開發的Handler --> <context:component-scan base-package="com.asd"></context:component-scan> <!-- 通過annotation-driven可以替代處理器對映和處理器介面卡--> <mvc:annotation-driven></mvc:annotation-driven> <!-- 2 自定義WebBinder--> <bean id="customBinder" name="" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> <!-- 配置validator --> <property name="validator" ref="validator"></property> </bean> <!-- 3.校驗器 --> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <!-- 校驗器 --> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property> <!-- 指定校驗器使用的資原始檔,如果不指定,則預設使用classpath下ValidationMessage.properties --> <property name="validationMessageSource" ref="messageSource"></property> </bean> <!-- 錯誤資訊配置檔案 --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <!-- 資原始檔名 --> <property name="basenames"> <list> <value>classpath:CustomValiationMessages</value> </list> </property> <!-- 檔案編碼 --> <property name="fileEncodings" value="UTF-8"></property> <!-- 快取時間 --> <property name="cacheSeconds" value="120"></property> </bean> <!-- 1.註解介面卡 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <!-- 註解介面卡中引用--> <property name="webBindingInitializer" ref="customBinder"></property> </bean> <!-- 4.檢視解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
2.CustomValiationMessages.properties
items.name.length.error=商品名稱長度限制在1~30個字元
items.createtime.is.notnull=商品生產日期不可為空
3.Items.java
public class Items{
...
//商品名稱長度限制在1~30個字元
@Size(min=1,max=30,message="{items.name.length.error}")
private String name;
@NotNull(message="{items.createtime.is.notnul}")
private Date createtime;
...
}
4.ItemsController.java
(引數POJO類前新增 @Validated 註解,後面新增引數 (BindingResult bindingResult); [email protected] @ModelAttribute(value=“itemsCustom”) ItemsCustom itemsCustom,BindingResult bindingResult,)
@Controller
@RequestMapping("/items")
public class ItemsController{
@Autowired
private ItemsService itemsService;
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(Model model,Integer id,HttpServlerRequest request,
@Validated @ModelAttribute(value="itemsCustom") ItemsCustom itemsCustom,BindingResult bindingResult,
MultipartFile picFile) throws Exception{
model.addAttribute("id",id);
if (picFile!=null&&picFile.getOriginalFilename()!=null&&picFile.getOriginalFilename().length()>0) {
//進行檔案上傳
String fielPath=request.getRealPath("/");
//上傳的原始檔名
String oldFileName=picFile.getOriginalFilename();
//新檔名
String newFileName=UUID.randomUUID()+oldFileName.subString(oldFileName.lastIndexOf("."));
//新檔案
File file=new File(fielPath+"images/"+newFileName);
//寫入檔案
picFile.transferTo(file);
//新圖片寫入到資料庫中
itemsForm.setPic(newFileName);
}
if (bindingResult.hasErrors()) {
List<ObjectError> errors=bindingResult.getAllErrors();
for (ObjectError error:errors) {
System.out.pringln(error.getDefaultMessage());
}
}
itemsService.updateItems(id,itemsCustom);
return "redirect:queryItems.action";
}
}
5. editItems.jsp
(4.ItemsController.java中列印輸出資訊時,有 getDefaultMessage() 方法:System.out.pringln(error.getDefaultMessage());
,所以 5. editItems.jsp頁面中顯示錯誤資訊時:${error.defaultMessage}
,get方法去掉 get,再首字母小寫;)
<body>
<!-- 顯示錯誤資訊 -->
<c:forEach items="${errors}" var="error">
${error.defaultMessage}<br/>
</c:forEach>
<form action="${pageContext.request.contextPath}/items/editItemsSubmit.action" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="${item.id}"/>
<table>
<tr><td>商品名稱:</td>
<td><input type="text" name="name" value="${itemsCustom.name}"></td></tr>
<tr><td>商品價格:</td>
<td><input type="text" name="price" value="${itemsCustom.price}"></td></tr>
<tr><td>商品圖片</td>
<c:if test="${itemsCustom.pic!=null}">
<img src="images/${itemsCustom.pic}" width="100" height="100"/><br/>
</c:if>
<input type="file" name="picFile"/>
</tr>
<tr><td>訂購日期:</td>
<td><input type="text" name="price" value="<fmt:formatDate value='${itemsCustom.createtime}' pattern="yyyy-MM-dd"/>"></td></tr>
<tr><td>商品描述:</td>
<td><input type="text" name="detail" value="${itemsCustom.detail}"></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="提交"/></td></tr>
</table>
</form>
</body>
執行結果頁面:
Validation分組校驗
需求:
針對不同的 Controller方法達到個性化驗證;比如:修改商品資訊,只校驗日期不為空;
1. 建立分組介面;(介面不定義方法,只作為一個標識)
2. 定義校驗規則屬於哪分組;(POJO類對應的欄位上相應的註解如 @Size、@NotNull 中新增 groups屬性,如:groups={ValidateGroup1.class}
,指明屬於哪個組; )
3. 在Controller方法中定義使用校驗組;(使用 @Validated 註解的 value 屬性指明分組:
@Validated(value={ValidateGroup1.class})
);
eg:
1.ValidateGroup1.java
public class ValidateGroup1{
//介面不定義方法,只作為一個標識
}
1.’ValidateGroup2.java
public class ValidateGroup2{
//介面不定義方法,只作為一個標識
}
2.Items.java
(對應的欄位上相應的註解如 @Size、@NotNull 中新增 groups屬性,如:groups={ValidateGroup1.class}
,指明屬於哪個組; )
public class Items{
...
//商品名稱長度限制在1~30個字元
@Size(min=1,max=30,message="{items.name.length.error}",groups={ValidateGroup2.class})
private String name;
@NotNull(message="{items.createtime.is.notnul}",groups={ValidateGroup1.class})
private Date createtime;
...
}
3.ItemsController.java
((引數POJO類前新增 @Validated 註解,@Validated(value={ValidateGroup1.class})
,value 指明哪個分組,後面新增引數 (BindingResult bindingResult);)
@Controller
@RequestMapping("/items")
public class ItemsController{
@Autowired
private ItemsService itemsService;
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(Model model,Integer id,HttpServlerRequest request,
@Validated(value={ValidateGroup1.class}) @ModelAttribute(value="itemsCustom") ItemsCustom itemsCustom,BindingResult bindingResult,
MultipartFile picFile) throws Exception{
model.addAttribute("id",id);
if (picFile!=null&&picFile.getOriginalFilename()!=null&&picFile.getOriginalFilename().length()>0) {
//進行檔案上傳
String fielPath=request.getRealPath("/");
//上傳的原始檔名
String oldFileName=picFile.getOriginalFilename();
//新檔名
String newFileName=UUID.randomUUID()+oldFileName.subString(oldFileName.lastIndexOf("."));
//新檔案
File file=new File(fielPath+"images/"+newFileName);
//寫入檔案
picFile.transferTo(file);
//新圖片寫入到資料庫中
itemsForm.setPic(newFileName);
}
if (bindingResult.hasErrors()) {
List<ObjectError> errors=bindingResult.getAllErrors();
for (ObjectError error:errors) {
System.out.pringln(error.getDefaultMessage());
}
}
itemsService.updateItems(id,itemsCustom);
return "redirect:queryItems.action";
}
}