springMVC学习(7)-springMVC校验
一、校验理解:
对于安全要求较高点建议在服务端进行校验。
控制层conroller:校验页面请求的参数的合法性。在服务端控制层conroller校验,不区分客户端类型(浏览器、手机客户端、远程调用)
业务层service(使用较多):主要校验关键业务参数,仅限于service接口中使用的参数。
持久层dao:一般是不校验
二、SpringMVC校验需求:
springmvc使用hibernate的校验框架validation(和hibernate没有任何关系)。
思路:
页面提交请求的参数,请求到controller方法中,使用validation进行校验。如果校验出错,将错误信息展示到页面。
具体需求:
商品修改,添加校验(校验商品名称长度,生产日期的非空校验)如果校验出错,在商品修改页面显示错误信息。
三、环境准备:
添加jar包:这里使用的是:
hibernate-validator-4.3.0-Final.jar;
jboss-logging-3.1.0.CR2.jar;
validation-api-1.0.0.GA.jar;
四、相关配置:
1)配置校验器:
1 <mvc:annotation-driven conversion-service="conversionService" validator="validator"> 2 </mvc:annotation-driven> 3 <!-- 校验器 --> 4 <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> 5 <!-- hibernate校验器--> 6 <property name="providerClass" value="org.hibernate.validator.HibernateValidator" /> 7 <!-- 指定校验使用的资源文件,在文件中配置校验错误信息,如果不指定则默认使用classpath下的ValidationMessages.properties --> 8 <property name="validationMessageSource" ref="messageSource" /> 9 </bean> 10 <!-- 校验错误信息配置文件 --> 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 <!-- 对资源文件内容缓存时间,单位秒 --> 21 <property name="cacheSeconds" value="120" /> 22 </bean>
2)由于这里是在Contoller中的形参(ItemsCustom)来接收参数,在pojo中添加校验规则:
1 public class Items { 2 private Integer id; 3 4 //校验名称在1到30字符中间 5 //message是提示校验出错显示的信息 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 //非空校验 12 @NotNull(message="{items.createtime.isNUll}") 13 private Date createtime; 14 15 .... 16 }
3)配置校验错误提示信息文件 -- /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