标签: springmvc前端
[TOC]java
本文主要介绍springmvc校验,包括环境准备,校验器配置,pojo张添加校验规则,捕获和显示检验错误信息以及分组校验简单示例。git
项目中,一般使用较可能是前端的校验,好比页面中js校验。对于安全要求较高点建议在服务端进行校验。github
服务端校验:spring
springmvc使用hibernate的校验框架validation(和hibernate没有任何关系)。api
校验思路:浏览器
页面提交请求的参数,请求到controller方法中,使用validation进行校验。若是校验出错,将错误信息展现到页面。缓存
具体需求:安全
商品修改,添加校验(校验商品名称长度,生产日期的非空校验),若是校验出错,在商品修改页面显示错误信息。mvc
咱们须要三个jar包:
这里咱们添加maven依赖
<!-- hibernate 校验 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.4.Final</version> </dependency>
查看maven依赖树
[INFO] \- org.hibernate:hibernate-validator:jar:5.2.4.Final:compile [INFO] +- javax.validation:validation-api:jar:1.1.0.Final:compile [INFO] +- org.jboss.logging:jboss-logging:jar:3.2.1.Final:compile [INFO] \- com.fasterxml:classmate:jar:1.1.0:compile
能够看到,另外两个jar包被hibernate-validator
依赖,因此不用再额外添加了。
<!-- 校验器 --> <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>classpath:CustomValidationMessages</value> </list> </property> <!-- 资源文件编码格式 --> <property name="fileEncodings" value="utf-8" /> <!-- 对资源文件内容缓存时间,单位秒 --> <property name="cacheSeconds" value="120" /> </bean>
<mvc:annotation-driven conversion-service="conversionService" validator="validator"> </mvc:annotation-driven>
#添加校验的错误提示信息 items.name.length.error=请输入1到30个字符的商品名称 items.createtime.isNUll=请输入商品的生产日期
在ItemsCustom.java中添加校验规则:
public class Items { private Integer id; //校验名称在1到30字符中间 //message是提示校验出错显示的信息 //groups:此校验属于哪一个分组,groups能够定义多个分组 @Size(min=1,max=30,message="{items.name.length.error}") private String name; private Float price; private String pic; //非空校验 @NotNull(message="{items.createtime.isNUll}") private Date createtime;
@RequestMapping("/editItemsSubmit") public String editItemsSubmit( Model model, HttpServletRequest request, 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); //能够直接使用model将提交pojo回显到页面 model.addAttribute("items", itemsCustom); // 出错从新到商品修改页面 return "items/editItems"; }
<!-- 显示错误信息 --> <c:if test="${allErrors!=null }"> <c:forEach items="${allErrors }" var="error"> ${ error.defaultMessage}<br/> </c:forEach> </c:if>
1.校验分组
public interface ValidGroup1 { //接口中不须要定义任何方法,仅是对不一样的校验规则进行分组 //此分组只校验商品名称长度 }
2.在校验规则中添加分组
//校验名称在1到30字符中间 //message是提示校验出错显示的信息 //groups:此校验属于哪一个分组,groups能够定义多个分组 @Size(min=1,max=30,message="{items.name.length.error}",groups = {ValidGroup1.class}) private String name;
3.在controller方法使用指定分组的校验
// value={ValidGroup1.class}指定使用ValidGroup1分组的校验 @RequestMapping("/editItemsSubmit") public String editItemsSubmit( Model model, HttpServletRequest request, Integer id, @Validated(value = ValidGroup1.class)ItemsCustom itemsCustom, BindingResult bindingResult)throws Exception {