• 简介

  项目中,通常使用较多是前端的校验,比如页面中js校验。对于安全要求较高点建议在服务端进行校验。

  服务端校验:

  控制层conroller:校验页面请求的参数的合法性。在服务端控制层conroller校验,不区分客户端类型(浏览器、手机客户端、远程调用)

  业务层service(使用较多):主要校验关键业务参数,仅限于service接口中使用的参数。

  持久层dao:一般是不校验的。

  • springmvc校验

  springmvc使用hibernate的校验框架validation。

  校验思路:页面提交请求的参数,请求到controller方法中,使用validation进行校验。如果校验出错,将错误信息展示到页面。

  • 环境准备

  hibernate的校验框架validation所需要jar包:

  • 配置校验器
 <!-- 校验器 -->
<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>
  • 在POJO中添加校验规则
 //字符长度在1-30个字符之间
//message提示校验出错显示的信息
@Size(min=1,max=30,message="{items.length.error.message}")
private String name;
//创建日期非空校验
@NotNull(message="{items.createtime.isNull}")
private Date createtime;
  • 校验信息配置文件

  CustomValidationMessages.properties

  • 捕获校验错误和页面显示校验错误信息 

  

 // 商品信息修改提交
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(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());
}
//将错误信息回显到页面
request.setAttribute("allerrors", allerrors);
return "items/editItems";
}
// 调用service更新商品信息,页面需要将商品信息传到此方法
itemsService.updateItems(id, itemsCustom); // 重定向到商品查询列表
// return "redirect:queryItems.action";
// 页面转发
return "forward:queryItems.action";
// return "success";
}

  页面显示错误信息:

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

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

  解决方法:定义多个校验分组(其实是一个java接口),分组中定义有哪些规则,每个controller方法使用不同的校验分组。

  1、校验分组

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

  2、在校验中添加分组信息

 @Size(min=1,max=30,message="{items.length.error.message}",groups={ValidGroup1.class})
private String name;

  3、在controller方法使用指定分组的校验

 public String editItemsSubmit(HttpServletRequest request, Integer id,
@Validated(value={ValidGroup1.class}) ItemsCustom itemsCustom,BindingResult bindingResult) throws Exception

  主要添加如下信息:@Validated(value={ValidGroup1.class})

  注解的主要用法:

@Null   被注释的元素必须为 null

@NotNull    被注释的元素必须不为 null

@AssertTrue     被注释的元素必须为 true

@AssertFalse    被注释的元素必须为 false

@Min(value)     被注释的元素必须是一个数字,其值必须大于等于指定的最小值

@Max(value)     被注释的元素必须是一个数字,其值必须小于等于指定的最大值

@DecimalMin(value)  被注释的元素必须是一个数字,其值必须大于等于指定的最小值

@DecimalMax(value)  被注释的元素必须是一个数字,其值必须小于等于指定的最大值

@Size(max=, min=)   被注释的元素的大小必须在指定的范围内

@Digits (integer, fraction)     被注释的元素必须是一个数字,其值必须在可接受的范围内

@Past   被注释的元素必须是一个过去的日期

@Future     被注释的元素必须是一个将来的日期

@Pattern(regex=,flag=)  被注释的元素必须符合指定的正则表达式

Hibernate Validator 附加的 constraint

@NotBlank(message =)   验证字符串非null,且长度必须大于0

@Email  被注释的元素必须是电子邮箱地址

@Length(min=,max=)  被注释的字符串的大小必须在指定的范围内

@NotEmpty   被注释的字符串的必须非空

@Range(min=,max=,message=)  被注释的元素必须在合适的范围内

SpringMVC学习--校验的更多相关文章

  1. 【SpringMVC学习06】SpringMVC中的数据校验

    这一篇博文主要总结一下springmvc中对数据的校验.在实际中,通常使用较多是前端的校验,比如页面中js校验,对于安全要求较高的建议在服务端也要进行校验.服务端校验可以是在控制层conroller, ...

  2. SpringMVC学习笔记之二(SpringMVC高级参数绑定)

    一.高级参数绑定 1.1 绑定数组 需求:在商品列表页面选中多个商品,然后删除. 需求分析:功能要求商品列表页面中的每个商品前有一个checkbok,选中多个商品后点击删除按钮把商品id传递给Cont ...

  3. (转)SpringMVC学习(十二)——SpringMVC中的拦截器

    http://blog.csdn.net/yerenyuan_pku/article/details/72567761 SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter, ...

  4. springmvc学习笔记(10)-springmvc注解开发之商品改动功能

    springmvc学习笔记(10)-springmvc注解开发之商品改动功能 标签: springmvc springmvc学习笔记10-springmvc注解开发之商品改动功能 需求 开发mappe ...

  5. 【springmvc学习】常用注解总结

    @Controller 在springmvc中,我们用它来告诉前端控制器,他这个类是controller,也就是springmvc的一个对象了,我们在spring.xml配置文件中用<conte ...

  6. SpringMVC学习系列-后记 解决GET请求时中文乱码的问题

    SpringMVC学习系列-后记 解决GET请求时中文乱码的问题 之前项目中的web.xml中的编码设置: <filter> <filter-name>CharacterEnc ...

  7. 史上最全的SpringMVC学习笔记

    SpringMVC学习笔记---- 一.SpringMVC基础入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于Spring ...

  8. SpringMVC学习系列-后记 开启项目的OpenSessionInView

    在系列的 SpringMVC学习系列(12) 完结篇 的示例项目中,由于当时考虑到OpenSessionInView会对性能有一定的影响,所以就没有配置项目的OpenSessionInView.在ma ...

  9. SpringMVC学习系列-后记 结合SpringMVC和Hibernate-validator,根据后台验证规则自动生成前台的js验证代码

    在SpringMVC学习系列(6) 之 数据验证中我们已经学习了如何结合Hibernate-validator进行后台的数据合法性验证,但是通常来说后台验证只是第二道保险,为了更好的用户体验会现在前端 ...

随机推荐

  1. oracle之报错:ORA-00054: 资源正忙,要求指定 NOWAIT

    oracle之报错:ORA-00054: 资源正忙,要求指定 NOWAIT 问题如下: SQL> conn scott/tiger@vm_database Connected to Oracle ...

  2. web报表工具FineReport常用函数的用法总结(报表函数)

    说明:本次总结中,凡是以tableName或viewName作为参数因子的.函数在调用的时候均按照先从私有数据源中查找,然后再从公有数据源中查找的顺序. CLASS CLASS(object):返回o ...

  3. [转]SQL 操作结果集 -并集、差集、交集、结果集排序

    本文转自:http://www.cnblogs.com/kissdodog/archive/2013/06/24/3152743.html 操作结果集 为了配合测试,特地建了两个表,并且添加了一些测试 ...

  4. Use getopt() & getopt_long() to Parse Arguments

    Today I came across a function [getopt] by accident. It is very useful to parse command-line argumen ...

  5. androidSDK无法更新的解决方法之一

    方法来源于: http://www.eoeandroid.com/thread-281075-1-1.html 试试这个,能解决国内访问Google服务器的困难启动 Android SDK Manag ...

  6. 由项目中一个hash2int函数引发的思考

    hash2int /** * 计算一个字符串的md5折算成int返回 * @param type $str * @return type */ function hash2int($str) { $m ...

  7. Twitter Snowflake 的Java实现

    在关闭显示的情况下, 可以达到每毫秒3万个的生成速度 /** * An Implementation of Twitter Snowflake ID Generator */ public class ...

  8. How to regress out unwanted vectors

    Source: http://stats.stackexchange.com/questions/117840/how-to-regress-out-some-variables Answer in ...

  9. 未能正确加载包“Microsoft.Data.Entity.Design.Package.MicrosoftDataEntityDesignPackage

    本文出处:http://blog.sina.com.cn/s/blog_6fe3efa301016i64.html vs 2005 ,vs 2008, vs 2010,安装后有时出现这个错误(我的机器 ...

  10. flask+sqlite3+echarts2+ajax数据可视化--静态图

    结构: /www | |-- /static | | | |-- echarts.js(当然还有echarts原dist目录下的文件(夹)) | |-- /templates | | | |-- in ...