javascript
SpringMVC教程--Validation校验
Validation校驗
?
b/s系統中對http請求數據的校驗多數在客戶端進行,這也是出于簡單及用戶體驗性上考慮,但是在一些安全性要求高的系統中服務端校驗是不可缺少的,本節主要學習springmvc實現控制層添加校驗。
Spring3支持JSR-303驗證框架,JSR-303是JAVA EE 6中的一項子規范,叫做Bean Validation,官方參考實現是Hibernate Validator(與Hibernate ORM沒有關系),JSR 303用于對Java Bean中的字段的值進行驗證。
1.1?需求
對商品信息進行校驗,是否必須,輸入數據合法性。
?
1.2?加入jar包
?
?
1.3?配置validator
?
<!-- 校驗錯誤信息配置文件 --><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" /><property name="cacheSeconds" value="120" /></bean><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>?
?
1.4?將validator加到處理器適配器
配置方式1:
<!-- 自定義webBinder --><bean id="customBinder"class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"><property name="validator" ref="validator" /></bean>?
<!-- 注解適配器 --><beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"><property name="webBindingInitializer" ref="customBinder"></property></bean>?
配置方式2:
<mvc:annotation-driven validator="validator"> </mvc:annotation-driven>?
?
1.5?添加驗證規則
?
public class Items {private Integer id;@Size(min=1,max=30,message="{item.name.length.illigel}")private String name;@NotEmpty(message="{pic.is.null}")private String pic;1.6?錯誤消息文件CustomValidationMessages
?
item.name.length.illigel=商品在名稱在1到3個字符之間
pic.is.null=請上傳圖片
?
如果在eclipse中編輯properties文件無法看到中文則參考“Eclipse開發環境配置-indigo.docx”添加propedit插件。
?
1.7?捕獲錯誤
?
修改Controller方法:
// 商品修改提交@RequestMapping("/editItemSubmit")public String editItemSubmit(@Validated @ModelAttribute("item") Items items,BindingResult result,@RequestParam("pictureFile") MultipartFile[] pictureFile,Model model)throws Exception {//如果存在校驗錯誤則轉到商品修改頁面if (result.hasErrors()) {List<ObjectError> errors = result.getAllErrors();for(ObjectError objectError:errors){System.out.println(objectError.getCode());System.out.println(objectError.getDefaultMessage());}return "item/editItem";}注意:添加@Validated表示在對items參數綁定時進行校驗,校驗信息寫入BindingResult中,在要校驗的pojo后邊添加BingdingResult, 一個BindingResult對應一個pojo,且BingdingResult放在pojo的后邊。
?
商品修改頁面:
頁頭:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>?
在需要顯示錯誤信息地方:
<spring:hasBindErrors name="item"><c:forEach items="${errors.allErrors}" var="error">${error.defaultMessage }<br/></c:forEach></spring:hasBindErrors>說明:
<spring:hasBindErrors name="item">表示如果item參數綁定校驗錯誤下邊顯示錯誤信息。
?
1.8?分組校驗
如果兩處校驗使用同一個Items類則可以設定校驗分組。
?
定義分組:
分組就是一個標識,這里定義一個接口:
public interface ValidGroup1 {}public interface ValidGroup2 {}?
指定分組校驗:
public class Items {private Integer id;//這里指定分組ValidGroup1,此@Size校驗只適用ValidGroup1校驗@Size(min=1,max=30,message="{item.name.length.illigel}",groups={ValidGroup1.class})private String name;// 商品修改提交@RequestMapping("/editItemSubmit")public String editItemSubmit(@Validated(value={ValidGroup1.class}) @ModelAttribute("item") Items items,BindingResult result,@RequestParam("pictureFile") MultipartFile[] pictureFile,Model model)throws Exception {在@Validated中添加value={ValidGroup1.class}表示商品修改使用了ValidGroup1分組校驗規則,也可以指定多個分組中間用逗號分隔,
@Validated(value={ValidGroup1.class,ValidGroup2.class?})
總結
以上是生活随笔為你收集整理的SpringMVC教程--Validation校验的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringMVC教程--图片上传
- 下一篇: SpringMVC教程--异常处理器详解