对于后端的参数校验,我们一直在强调的验证规则,提示信息的重用。这不,springmvc通过集成Valid最大程序减少了我们的工作量。其实后端的参数过滤,是分几种请求来源的。每种的处理都不太一样,但是我们如果能重用验证规则,提示信息,那就很强大了。
1 常用的表单提交,需要页面返回错误信息
2 AJAX提交,需要JSON格式返回,或者XML
3 接口调用,同样需要对应的数据格式返回
对于这3类请求,我今天讲的是第3种,是可以重用第1种的资源和验证规则。它就是ControllerAdvice(控制建议)
1 /**
2 * Indicates the annotated class assists a "Controller".
3 *
4 * <p>Serves as a specialization of {@link Component @Component}, allowing for
5 * implementation classes to be autodetected through classpath scanning.
6 *
7 * <p>It is typically used to define {@link ExceptionHandler @ExceptionHandler},
8 * {@link InitBinder @InitBinder}, and {@link ModelAttribute @ModelAttribute}
9 * methods that apply to all {@link RequestMapping @RequestMapping} methods.
10 *
11 * @author Rossen Stoyanchev
12 * @since 3.2
13 */
2 * Indicates the annotated class assists a "Controller".
3 *
4 * <p>Serves as a specialization of {@link Component @Component}, allowing for
5 * implementation classes to be autodetected through classpath scanning.
6 *
7 * <p>It is typically used to define {@link ExceptionHandler @ExceptionHandler},
8 * {@link InitBinder @InitBinder}, and {@link ModelAttribute @ModelAttribute}
9 * methods that apply to all {@link RequestMapping @RequestMapping} methods.
10 *
11 * @author Rossen Stoyanchev
12 * @since 3.2
13 */
中文的大概意思就是:
A 定义异常处理
B 初始化binder,比如一些类型转换,自定义验证等等
C 设置ModelAttribute的值
看到没有,异常处理。刚好spring有提供 MethodArgumentNotValidException这个异常,而这个异常就是处理参数验证不通过会抛出的。
哈哈哈,太好了。这样,我就可以在这里面,去封装Valid的异常
如图
里面的processValidationError方法会处理具体异常的返回值并以JSON输出,大功告成,下周再贴出整体代码链接。
当这样处理之后,我们的resetful的接口只用处理真正的业务,完全不用做常用的参数检查。
相关推荐
springmvc权限验证demo
《使用Validator做SpringMVC的验证框架》教程源码 教程地址: http://blog.csdn.net/devefx/article/details/51565139 http://blog.csdn.net/devefx/article/details/51567533 ...
springmvc注解式控制器的数据验证、类型转换及格式化 SpringMVC数据验证 参数传递
SpringMVC数据验证——注册用户格式的验证实例,具体过程和效果看博文http://blog.csdn.net/evankaka/article/details/45789283
hibernate-validator, jboss-logging validation-api等包
SpringMVC入门很简单之数据验证,具体参考博文:http://www.cnblogs.com/liukemng/tag/SpringMVC/
springmvc拦截器实现登录验证
springmvc返回json的全局异常统一处理demo,有问题可以留言。
这个能很简单并快捷的配置完成数据校验,提高安全性,并提高开发效率,以及提高系统的安全性以及高效性
Maven+SpringMVC实现统一异常处理
采用springmvc+mybatis,搭建部分大致跟网上其他资料差不多,唯一不同的加入了统一错误处理,为了方便开发人员开发,所有错误码用一张表存在数据库中,然后由应用将整表缓存,缓存采用的spring自带的cache,开发中...
《使用Validator做SpringMVC的验证框架》教程源码 教程地址: http://blog.csdn.net/devefx/article/details/51565139 http://blog.csdn.net/devefx/article/details/51567533 ...
springmvc注解验证例子,对于刚学的开发者,很容易入手
springmvc验证需要的jar
本项目为springMVC表单验证简单实例,支持国际化,发布就可以试验效果, 访问路如:http://localhost:8080/springMVC_Validator/register.mvc
Springmvc请求处理方法参数Springmvc请求处理方法参数
springmvc异常处理的博文如下: http://blog.csdn.net/dlf123321/article/details/50756003
个人整理的很好的springmvc注解实现用户注册功能。方便扩展其他功能。
springmvc+spring线程池处理http并发请求数据同步控制问题
企业级开发-SpringMVC使用拦截器实现用户登录权限验证实验报告