一、校验理解:

对于安全要求较高点建议在服务端进行校验。

控制层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)配置校验器:

 <mvc:annotation-driven conversion-service="conversionService" validator="validator">
</mvc:annotation-driven>
<!-- 校验器 -->
<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>

2)由于这里是在Contoller中的形参(ItemsCustom)来接收参数,在pojo中添加校验规则:

 public class Items {
private Integer id; //校验名称在1到30字符中间
//message是提示校验出错显示的信息
@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; ....
}

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

4)在controller中编写校验、捕获校验错误信息:

 //商品信息修改提交
// 在需要校验的pojo前边添加@Validated,在需要校验的pojo后边添加BindingResult
// bindingResult接收校验出错信息
// 注意:@Validated和BindingResult bindingResult是配对出现,并且形参顺序是固定的(一前一后)。
@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); return "items/editItems";
} itemsService.updateItems(id, itemsCustom);
return "success";
}

5)jsp页面展示错误信息:

 <!-- 显示错误信息 -->
<c:if test="${allErrors!=null}">
错误信息:<br/>
<c:forEach items="${allErrors}" var="error">
${error.defaultMessage}<br/>
</c:forEach>
</c:if>

效果:后台打印:

前台展示:

---------------------------------------------------------------------------------------------------------------------------------------

分组校验:

需求:

在pojo中定义校验规则,而pojo是被多个 controller所共用,当不同的controller方法对同一个pojo进行校验,但是每个controller方法需要不同的校验。

解决办法:

定义多个校验分组(其实是一个java接口),分组中定义有哪些规则

每个controller方法使用不同的校验分组

1)定义两个校验分组:

package com.cy.controller.validation;

/**
* 校验分组
* @author chengyu
*
*/
public interface ValidGroup1 {
//接口中不需要定义任何方法,仅是对不同的校验规则进行分组
//此分组只校验商品名称长度
} .... public interface ValidGroup2 { }

2)在校验规则中添加分组,Items中:

 public class Items {
private Integer id; //校验名称在1到30字符中间
//message是提示校验出错显示的信息
//groups:此校验属于哪个分组,groups可以定义多个分组
@Size(min=1,max=30,message="{items.name.length.error}",groups={ValidGroup1.class})
private String name;
private Float price;
private String pic; //非空校验
@NotNull(message="{items.createtime.isNUll}")
private Date createtime; ..... }

3)在Controller方法中指定分组的校验:

 //商品信息修改提交
// 在需要校验的pojo前边添加@Validated,在需要校验的pojo后边添加BindingResult
// bindingResult接收校验出错信息
// 注意:@Validated和BindingResult bindingResult是配对出现,并且形参顺序是固定的(一前一后)。
// 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 { if(bindingResult.hasErrors()){
List<ObjectError> allErrors = bindingResult.getAllErrors();
for(ObjectError objectError : allErrors){
System.out.println(objectError.getDefaultMessage());
} // 将错误信息传到页面
model.addAttribute("allErrors", allErrors); return "items/editItems";
} itemsService.updateItems(id, itemsCustom);
return "success";
}

后台打印:

前台页面:

springMVC学习(7)-springMVC校验的更多相关文章

  1. (转)SpringMVC学习(六)——SpringMVC高级参数绑定与@RequestMapping注解

    http://blog.csdn.net/yerenyuan_pku/article/details/72511749 高级参数绑定 现在进入SpringMVC高级参数绑定的学习,本文所有案例代码的编 ...

  2. (转)SpringMVC学习(三)——SpringMVC的配置文件

    http://blog.csdn.net/yerenyuan_pku/article/details/72231527 读者阅读过SpringMVC学习(一)——SpringMVC介绍与入门这篇文章后 ...

  3. (转)SpringMVC学习(一)——SpringMVC介绍与入门

    http://blog.csdn.net/yerenyuan_pku/article/details/72231272 SpringMVC介绍 SpringMVC是什么? SpringMVC和Stru ...

  4. (转)SpringMVC学习(五)——SpringMVC的参数绑定

    http://blog.csdn.net/yerenyuan_pku/article/details/72511611 SpringMVC中的参数绑定还是蛮重要的,所以单独开一篇文章来讲解.本文所有案 ...

  5. springMVC学习(3)-springMVC和mybatis整合

    一.需求:使用springmvc和mybatis完成商品列表查询. 二.整合思路:springMVC+mybaits的系统架构: 1步):整合dao层 mybatis和spring整合,通过sprin ...

  6. (转)SpringMVC学习(二)——SpringMVC架构及组件

    http://blog.csdn.net/yerenyuan_pku/article/details/72231385 相信大家通过前文的学习,已经对SpringMVC这个框架多少有些理解了.还记得上 ...

  7. SpringMVC学习(二)——SpringMVC架构及组件(及其运行原理)-转载

    相信大家通过前文的学习,已经对SpringMVC这个框架多少有些理解了.还记得上一篇文章中SpringMVC的处理流程吗?  这个图大致描述了SpringMVC的整个处理流程,这个流程图还是相对来说比 ...

  8. SpringMVC 学习 十一 springMVC控制器向jsp或者别的控制器传递参数的四种方法

    以后的开发,大部分是发送ajax,因此这四种传递参数的方法,并不太常用.作为了解吧 第一种:使用原生 Servlet 在控制器的响应的方法中添加Servlet中的一些作用域:HttpRequestSe ...

  9. SpringMVC学习(十一)——SpringMVC实现Resultful服务

    http://blog.csdn.net/yerenyuan_pku/article/details/72514034 Restful就是一个资源定位及资源操作的风格,不是标准也不是协议,只是一种风格 ...

随机推荐

  1. L1-024 后天

    如果今天是星期三,后天就是星期五:如果今天是星期六,后天就是星期一.我们用数字1到7对应星期一到星期日.给定某一天,请你输出那天的“后天”是星期几. 输入格式: 输入第一行给出一个正整数D(1 ≤ D ...

  2. Translate Exercises(4)

    周五翻译课记录. ---------------------------------- (1)and it is imagined by many that the operations of the ...

  3. Vue.js 源码学习笔记 - 细节

     1. this._eventsCount = { }    这是为了避免不必要的深度遍历: 在有广播事件到来时,如果当前 vm 的 _eventsCount 为 0, 则不必向其子 vm 继续传播该 ...

  4. IOS控件大全及控件大小

    一 视图UIView和UIWindow iphone视图的规则是:一个窗口,多个视图.UIWindow相当于电视机,UIViews相当于演员. 1.显示数据的视图 下面几个类可在屏幕上显示信息: UI ...

  5. CentOS 6.5使用yum快速搭建LAMP环境

    由于这里采用yum方式安装,前提是我们必须配置好yum源.为了加快下载速度,建议使用网易的yum源. 这种方式对于初学者来说,非常方便,但是可定制性不强,而且软件版本较低.一般用于实验和学习环境. 1 ...

  6. Windows系统80端口被占用

    1.查看系统端口被占用情况, 执行命令netstat -ano ,可以查看到被占用的端口对于的PID. 2. 打开任务管理器,然后点击“查看”→“选择PID”,勾上PID,再按PID排序,即可以看到8 ...

  7. Python+Requests接口测试教程(2):requests

    开讲前,告诉大家requests有他自己的官方文档:http://cn.python-requests.org/zh_CN/latest/ 2.1 发get请求 前言requests模块,也就是老污龟 ...

  8. linux配置禁用启用IPv6

    IPv6被认为是IPv4的替代产品,它用来解决现有IPv4地址空间即将耗尽的问题.但目前,开启IPv6可能会导致一些问题.因此有时我们需要关闭IPv6.下面是IPv6的关闭方法应该适用于所有主流的Li ...

  9. MATLAB安装教程

    1.资源下载 下载官方安装包R2015b_win64.(文件太大,没上传资源) 下载破解文件包,解压其中的相应压缩包(一般是win64那个压缩包) 下载地址:链接:http://pan.baidu.c ...

  10. memcpy - how to copy float* to float* variable

    how to copy float* to float* float* seg_segmap = new float[OUTPUT_H * OUTPUT_W]; float* temp = new f ...