springmvc教程:利用Validation进行参数校验

本人花费半年的时间总结的《Java面试指南》已拿腾讯等大厂offer,已开源在github ,欢迎star!

本文GitHub https://github.com/OUYANGSIHAI/JavaInterview 已收录,这是我花了6个月总结的一线大厂Java面试总结,本人已拿大厂offer,欢迎star

原文链接:blog.ouyangsihai.cn >> springmvc教程:利用Validation进行参数校验

上传图片

1.1 配置虚拟目录

1.2 配置解析器

Validation校验

b/s系统中对http请求数据的校验多数在客户端进行,这也是出于简单及用户体验性上考虑,但是在一些安全性要求高的系统中服务端校验是不可缺少的,本节主要学习springmvc实现控制层添加校验。

Spring3支持JSR-303验证框架,JSR-303是JAVA EE 6中的一项子规范,叫做Bean Validation,官方参考实现是Hibernate Validator(与Hibernate ORM没有关系),JSR 303用于对Java Bean中的字段的值进行验证。

1.1 需求

对商品信息进行校验,是否必须,输入数据合法性。

1.2 加入jar包

1.3 配置validator


<!-- 校验错误信息配置文件 -->

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

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

1.4 将validator加到处理器适配器

配置方式1:


<!-- 自定义webBinder -->

<bean id="customBinder"

class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">

<property name="validator" ref="validator" />

</bean>

<!-- 注解适配器 -->

<bean

class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">

<property name="webBindingInitializer" ref="customBinder"></property>

</bean>

配置方式2:


<mvc:annotation-driven validator="validator"> </mvc:annotation-driven>

1.5 添加验证规则


public class Items {

    private Integer id;

    @Size(min=1,max=30,message="{item.name.length.illigel}")

    private String name;

    @NotEmpty(message="{pic.is.null}")

    private String pic;

1.6 错误消息文件CustomValidationMessages

item.name.length.illigel=商品在名称在1到3个字符之间

pic.is.null=请上传图片

如果在eclipse中编辑properties文件无法看到中文则参考“Eclipse开发环境配置-indigo.docx”添加propedit插件。

1.7 捕获错误

修改Controller方法:


// 商品修改提交

@RequestMapping("/editItemSubmit")
public String editItemSubmit(@Validated @ModelAttribute("item") Items items,BindingResult result, @RequestParam("pictureFile") MultipartFile[] pictureFile,Model model) throws Exception {

  //如果存在校验错误则转到商品修改页面
  if (result.hasErrors()) {
    List<ObjectError> errors = result.getAllErrors();
    for(ObjectError objectError:errors){
      System.out.println(objectError.getCode());
      System.out.println(objectError.getDefaultMessage());
    }
  }
  return "item/editItem";
}

注意:添加@Validated表示在对items参数绑定时进行校验,校验信息写入BindingResult中,在要校验的pojo后边添加BingdingResult, 一个BindingResult对应一个pojo,且BingdingResult放在pojo的后边。

商品修改页面:

页头:


<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

在需要显示错误信息地方:


<spring:hasBindErrors name="item">

<c:forEach items="${errors.allErrors}" var="error">
  ${error.defaultMessage }<br/>
</c:forEach>

</spring:hasBindErrors>

说明:

<spring:hasBindErrors name=”item”>表示如果item参数绑定校验错误下边显示错误信息。

1.8 分组校验

如果两处校验使用同一个Items类则可以设定校验分组。

定义分组:

分组就是一个标识,这里定义一个接口:


public interface ValidGroup1 {

}

public interface ValidGroup2 {

}

指定分组校验:


public class Items {

    private Integer id;

//这里指定分组ValidGroup1,此@Size校验只适用ValidGroup1校验

    @Size(min=1,max=30,message="{item.name.length.illigel}",groups={ValidGroup1.class})

    private String name;

    // 商品修改提交
    @RequestMapping("/editItemSubmit")
    public String editItemSubmit(@Validated(value={ValidGroup1.class}) @ModelAttribute("item") Items items,BindingResult result,@RequestParam("pictureFile") MultipartFile[] pictureFile,Model model) throws Exception {
    }
}

在@Validated中添加value={ValidGroup1.class}表示商品修改使用了ValidGroup1分组校验规则,也可以指定多个分组中间用逗号分隔,

@Validated(value={ValidGroup1.class,ValidGroup2.class })

1.3 jar包

_CommonsMultipartResolver_解析器依赖commons-fileupload和commons-io,加入如下jar包:

1.4 单个图片上传

1、controller:


//商品修改提交
@RequestMapping("/editItemSubmit")
public String editItemSubmit(Items items, MultipartFile pictureFile) throws Exception{

  //原始文件名称
  String pictureFile_name =  pictureFile.getOriginalFilename();

  //新文件名称
  String newFileName = UUID.randomUUID().toString()+pictureFile_name.substring(pictureFile_name.lastIndexOf("."));

  //上传图片
  File uploadPic = new java.io.File("F:/develop/upload/temp/"+newFileName);

  if(!uploadPic.exists()){
      uploadPic.mkdirs();
  }

  //向磁盘写文件

  pictureFile.transferTo(uploadPic);

  .....
}

2、 页面:

form添加enctype=”multipart/form-data”:


<form id="itemForm" action="${pageContext.request.contextPath }/item/editItemSubmit.action" method="post" enctype="multipart/form-data">

  <input type="hidden" name="pic" value="${item.pic }" />
</form>

file的name与controller形参一致:


<tr>

<td>商品图片</td>

<td><c:if test="${item.pic !=null}">

<img src="/pic/${item.pic}" width=100 height=100 />

<br />

</c:if> <input type="file" name="pictureFile" /></td>

</tr><
本人花费半年的时间总结的《Java面试指南》已拿腾讯等大厂offer,已开源在github ,欢迎star!

本文GitHub https://github.com/OUYANGSIHAI/JavaInterview 已收录,这是我花了6个月总结的一线大厂Java面试总结,本人已拿大厂offer,欢迎star

原文链接:blog.ouyangsihai.cn >> springmvc教程:利用Validation进行参数校验


 上一篇
推荐一个很牛逼的Github项目:本人历时半年完成的《Java面试指南》已拿大厂offer 推荐一个很牛逼的Github项目:本人历时半年完成的《Java面试指南》已拿大厂offer
今天给大家分享一份【Java 面试 + Java 后端技术学习指南】:一份通向理想互联网公司的面试指南,包括 Java,技术面试必备基础知识、Leetcode、计算机操作系统、计算机网络、系统设计、分布式、数据库(MySQL、Redis)、
下一篇 
springmvc教程:使用json进行数据传输详解 springmvc教程:使用json进行数据传输详解
1.1 @RequestBody作用: @RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容转换为json、xml等格式的数据并绑定到cont