1 项目中,通常使用较多是前端的校验,比如页面中js校验。对于安全要求较高建议使用服务端校验。
2 服务端校验:
(1)控制层controller:效验页面请求的参数的合法性,在服务端控制层conroller校验,不区分客户端类型(浏览器、手机客户端、远程调用)
(2)业务层service(使用较多):主要校验关键业务参数,仅限于service接口中使用的参数。
(3)持久层dao:一般是不校验的。
3 校验思路:
页面提交请求的参数,请求到controller方法中,使用validation进行校验。如果校验出错,将错误信息展示到页面。
(1) 需要的jar包(maven):
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.3.0.Final</version>
</dependency>
(2) 在SpringMVC配置文件中添加配置校验器
<!--validation校验-->
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<!-- hibernate校验器-->
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<!-- 指定校验使用的资源文件,在文件中配置校验错误信息,如果不指定则默认使用classpath下的ValidationMessages.properties -->
<property name="validationMessageSource" ref="messageSource" />
</bean>
<!-- 校验错误信息配置文件 -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!-- 资源文件名-->
<property name="basenames">
<list>
<value>CustomValidationMessages</value>
</list>
</property>
<!-- 资源文件编码格式 -->
<property name="fileEncodings" value="utf-8" />
<!-- 对资源文件内容缓存时间,单位秒 -->
<property name="cacheSeconds" value="120" />
</bean>
(3) 校验器注入到处理器适配器中
<mvc:annotation-driven conversion-service="conversionService" validator="validator"/>
(4) 在pojo校验错误信息
private int id;
@Size(min = 1,max = 5,message = "items.name.length")
private String name;
private float price;
private String detail;
private String pic;
@NotNull(message = "items.time.error")
private Date createtime;
get set 方法略。。。。
(5) 在CustomValidationMessages.properties配置校验错误信息
items.name.length = 请输入1-5位字符
items.time.error = 时间不能为空
(6) 捕获和显示校验错误信息
@RequestMapping(value = "/editItemsSubmit")
public String editItemsSubmit(Model model,Integer id, @Validated ItemsCustom itemsCustom, BindingResult bindingResult) throws Exception {
if(bindingResult.hasErrors()){
List<ObjectError> allErrors = bindingResult.getAllErrors();
for (ObjectError objectError:allErrors){
System.out.println(objectError.getDefaultMessage());
}
model.addAttribute("allErrors",allErrors);
return "editItems";
}
itemsService.updateItems(id,itemsCustom);
return "success";
}
(7) 页面显示
<c:if test="${allErrors!=null}">
<c:forEach items="${allErrors}" var="error">
${error.defaultMessage}
</c:forEach>
</c:if>
3 测试
4 存在问题
在配置完成validation校验后,无法正确显示CustomValidationMessages.properties配置中的信息,显示为实体类中配置效验的路径。猜测可能没有去调用properties配置文件。
暂行解决办法,不引用CustomValidationMessages.properties文件,直接在pojo上给出异常信息
@Size(min = 1,max = 5,message = "请输入1-5位字符")
private String name;
省略get set方法。。。。
5 分组效验
定义多个校验分组(其实是一个java接口),分组中定义有哪些规则
每个controller方法使用不同的校验分组
(1)校验分组
public interface ValidGroup1 {
//接口中不需要定义任何方法,仅是对不同的校验规则进行分组
//此分组只校验商品名称长度
}
(2)在校验规则中添加分组
@Size(min = 1,max = 5,message = "请输入1-5位字符",groups = {ValidGroup1.class})
private String name;
(3)在controller方法使用指定分组的校验
public String editItemsSubmit(Model model, Integer id,
@Validated(value = ValidGroup1.class) ItemsCustom itemsCustom,
BindingResult bindingResult) throws Exception {
}
6 数据回显
(1)springmvc默认对pojo数据进行回显
pojo数据传入controller方法后,springmvc自动将pojo数据放到request域,key等于pojo类型(首字母小写)
使用@ModelAttribute指定pojo回显到页面request中的key
public String editItemsSubmit(Model model, Integer id,
@ModelAttribute("itemsCustom")
@Validated(value = ValidGroup1.class) ItemsCustom itemsCustom,
BindingResult bindingResult) throws Exception {
}
(2)@ModelAttribute还可以将方法的返回值传到页面
controller
/**
*商品分类
* itemstypes表示最终将方法返回值放在request中的key
*/
@ModelAttribute("itemstypes")
public Map<String, String> getItemsTypes() {
Map<String, String> itemType = new HashMap<String, String>();
itemType.put("101", "数码");
itemType.put("102", "母婴");
return itemType;
}
jsp
商品类型:<select name="itemtype">
<c:forEach items="${itemstypes}" var="itemtype">
<option value="${itemtype.key}">${itemtype.value}</option>
</c:forEach>
</select>
(3)最简单的数据回显model(不使用@ModelAttribute)
@RequestMapping(value = "/editItemsSubmit")
public String editItemsSubmit(Model model, Integer id,@Validated(value = ValidGroup1.class) ItemsCustom itemsCustom, BindingResult bindingResult) throws Exception {
if (bindingResult.hasErrors()) {
List<ObjectError> allErrors = bindingResult.getAllErrors();
for (ObjectError objectError : allErrors) {
System.out.println(objectError.getDefaultMessage());
}
model.addAttribute("allErrors", allErrors);
//最简单的数据回显model
model.addAttribute("itemsCustom",itemsCustom);
return "editItems";
}
itemsService.updateItems(id, itemsCustom);
return "success";
}