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 值 |