Spring3 開始支持JSR-303 驗證框架,JSR-303 支持XML 風格的和註解風格的驗證,接下來咱們首先看一下如何和Spring集成。
一、添加jar 包:
此處使用Hibernate-validator 實現(版本:hibernate-validator-4.3.0.Final-dist.zip),將以下jar 包添加到classpath(WEB-INF/lib 下便可):
validation-api-1.0.0.GA.jar JSR-303 規範API 包
hibernate-validator-4.3.0.Final.jar Hibernate 參考實現
二、配置中添加對JSR-303驗證框架的支持
<!--如下validator ConversionService在使用mvc: annotation-driven 會自動註冊-->java
<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>
validationMessageSource屬性:指定國際化錯誤消息從哪裏取,此處使用以前定義的messageSource來獲取國際化消息;若是此處不指定該屬性,則默認到classpath下的ValidationMessages.properties取國際化錯誤消息。
經過ConfigurableWebBindingInitializer註冊validator:web
<bean id="webBindingInitializer"class="org.springframework. web.bind. support.ConfigurableWebBindingInitializer"> <property name="conversionService" ref="conversionService"/> <property name="validator" ref="validator"/> </bean>
三、在Spring配置中添加message配置spring
<bean id="messageSource「 class="org.springframework. context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="classpath: messages"/> <property name="fileEncodings" value="utf-8"/> <property name="cacheSeconds" value="120"/> </bean>
四、建立Model
api
public class UserModel{ @NotNull(message="{username.not. empty} ") private String username; }
經過@NotNull指定此username字段不容許爲空,當驗證失敗時將從以前指定的messageSource中獲取「username.not. empty」 對應的錯誤信息,此處只有經過「{錯誤消息鍵值} 」 格式指定的才能從messageSource獲取。
五、Controllermvc
@Controller public class HelloWorldController{@RequestMapping("/validate/hello") public String validate(@Valid@ModelAttribute("user")UserModeluser, Errors errors){ if(errors. hasErrors() ) { return "validate/error"; } return "redirect: /success"; } }
經過在命令對象上註解@Valid來告訴Spring MVC此命令對象在綁定完畢後須要進行JSR-303驗證,若是驗證失敗會將錯誤信息添加到errors錯誤對象中。app
驗證註解 | 驗證的數據類型 | 說明 |
@AssertFalse | Boolean,boolean | 驗證註解的元素值是false |
@AssertTrue | Boolean,boolean | 驗證註解的元素值是true |
@NotNull | 任意類型 | 驗證註解的元素值不是null |
@Null | 任意類型 | 驗證註解的元素值是null |
@Min(value=值) | BigDecimal,BigInteger, byte,short, int, long,等任何Number 或CharSequence(存儲的是數字)子類型 | 驗證註解的元素值大於等於@Min 指定的value 值 |
@Max(value=值) | 和@Min 要求同樣 | 驗證註解的元素值小於等於@Max 指定的value 值 |