SpringMVC拦截器与Filter过滤器

  • SpringMVC拦截器与Filter过滤器
  • Spring MVC拦截器的定义
  • SpringMVC拦截器的配置
  • SpringMVC拦截器HandlerInterceptor接口

SpringMVC拦截器与Filter过滤器

在系统中,经常需要在处理用户请求之前和之后执行一些行为,例如:检测用户的权限、或者将请求的信息记录到日志中,即:平常所说的“权限检测”及“日志记录”。
         当然不仅仅这些,所以需要一种机制,拦截用户的请求,在请求之后添加处理逻辑。
         SpringMVC提供了Interceptor拦截器机制,用于请求的预处理和后处理。
         相比过滤器,拦截器作用的范围比较小,而拦截器几乎可以过滤所有请求。
         拦截器的作用:
             [1]用户请求拦截处理;
             [2]针对一个或者多个或者全部的Controller返回结果进行拦截处理;
             [3]页面渲染之后,响应给浏览器之间进行拦截处理。
         过滤器和拦截器的区别?
             [1]过滤器在请求到达项目组间之前工作;拦截器在前端控制器之后工作;
             [2]过滤器依赖Servlet容器;拦截器是SpringMVC的,它不依赖于servlet容器,而是由Spring容器进行初始化;
             Note that a filter gets configured in web.xml, a HandlerInterceptor in the application context.
             [3]拦截器只能对action动态请求起作用(静态请求,例如:不会对js、css、img等静态资源的请求起到拦截作用);而过滤器可以对所有的请求起作用,无法实现细粒度的请求拦截;
             [4]在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次。
拦截器可以访问action上下文、值栈里的对象,而过滤器不能访问。
             [5]拦截器可以获取IOC容器中的各个bean,而过滤器就不太方便,这点很重要,在拦截器里注入一个service,可以调用业务逻辑。

Spring MVC拦截器的定义

需要实现HandlerInterceptor接口。

package com.xwd.interceptor;import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** @ClassName AppInterceptor* @Description: com.xwd.interceptor* @Auther: xiwd* @Date: 2022/3/1 - 03 - 01 - 22:12* @version: 1.0*/
public class AppInterceptor implements HandlerInterceptor {//properties//methods/*** 在请求到达定义的Handler处理器(Controller)之前,工作* @param request   请求对象* @param response  响应对象* @param handler   目标要调用的handler* @return  true-继续向前执行,可以到达handler(Controller层);false-拒绝继续执行* @throws Exception*/@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("AppInterceptor preHandle");/**///解决POST乱码问题//判断是否登录//用户权限控制System.out.println(handler);return true;}/*** handler处理单元返回ModelAndView对象时候工作* @param request* @param response* @param handler* @param modelAndView* @throws Exception*/@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("AppInterceptor postHandle");//在handler(Controller控制层)返回ModelAndView对象时候进行拦截//控制视图-修改//控制数据-敏感数据过滤(敏感词)}/*** 页面渲染完毕,但是还没有响应给浏览器客户端之前,工作* @param request* @param response* @param handler* @param ex* @throws Exception*/@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("AppInterceptor afterCompletion");//一般用于做资源的释放操作---该方法无论是否出现异常都会执行}
}

SpringMVC拦截器的配置

需要在SpringMVC配置文件中配置HandlerInterceptor接口。
(有别于Filter过滤器,需要在web.xml中使用filter标签配置)

  <!--注册拦截器--><mvc:interceptors><!--[1]拦截所有的URL请求,那么直接指定bean即可-->
<!--        <bean class="com.xwd.interceptor.AppInterceptor"></bean>--><!--[2]拦截特定的请求,需要使用mvc:interceptor标签来限定被拦截的访问路径--><mvc:interceptor><mvc:mapping path="/login.do"/><bean class="com.xwd.interceptor.AppInterceptor"></bean></mvc:interceptor></mvc:interceptors>

SpringMVC拦截器HandlerInterceptor接口

HandlerInterceptor接口中定义了3个方法,分别用于对某一个/某一些特定的请求进行预处理或者后处理。
    【1】HandlerInterceptor拦截器
         HandlerInterceptor是一个工作流程(workflow)接口,允许自定义request请求的处理执行链(handler execution chains)。对于某一组特定的handler(controller控制器),应用程序可以注册任意数量的自定义拦截器(Interceptor),在不改变原有接口实现类的前提下,实现一组通用处理行为。
     【2】HandlerInterceptor拦截器工作流程
         一个HandlerInterceptor(拦截器)在HandlerAdapter(处理器适配器)触发handler(控制器之前)被调用(具体是:default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)方法被调用——请求预处理)。
         拦截器机制可以实现一组切面(Aspects)的预处理操作,例如:权限检测(Authorization Checks)、或者一组通用的处理行为(例如:区域设置-locale或者主题修改theme changes),拦截器可以分解出重复性的代码,形成一组通用的操作。
             [0]在HandlerAdapter处理器适配器调用handler(Controller控制器)之前,preHandle()方法被调用;
             [1]在异步处理场景下,在没有调用postHandle()方法或者faterCompletion()方法之前(此时Handler/Controller控制器尚未执行完毕),处理器可能在一个独立线程中执行。
             [2]当并发处理器Handler(即:控制器)(concurrent handler)执行完毕,携带处理结果的Model、ModeAndView等对象被返回给HandlerAdapter处理器适配器时, postHandle()方法就会被调用,可以用于实现数据、视图的进一步处理或者数据过滤操作;
             [3]当HandlerAdapter处理器适配器将封装ModeAndView对象返回给DispatcherServlet前端处理器之后,前端处理器就开始调用ViewResolver视图解析器,处理得到View视图对象,在将View视图对象响应给前端浏览器之前,faterCompletion()方法就会被调用。通常用于实现资源清理工作。
        【3】SpringMVC拦截器适用场景:与细粒度预处理任务相关的功能实现,优先考虑通过实现HandlerInterceptor接口,定义拦截器的方式。尤其是:分解出通用处理代码、权限检查等。
                  Filter过滤器适用场景:Filter过滤器更适合用来处理request请求内容、view视图内容处理,例如:multipart表单和GZip压缩处理。

附:HandlerInterceptor处理器拦截器接口源码

public interface HandlerInterceptor {/*** Intercept the execution of a handler. Called after HandlerMapping determined* an appropriate handler object, but before HandlerAdapter invokes the handler.* <p>DispatcherServlet processes a handler in an execution chain, consisting* of any number of interceptors, with the handler itself at the end.* With this method, each interceptor can decide to abort the execution chain,* typically sending an HTTP error or writing a custom response.* <p><strong>Note:</strong> special considerations apply for asynchronous* request processing. For more details see* {@link org.springframework.web.servlet.AsyncHandlerInterceptor}.* <p>The default implementation returns {@code true}.* @param request current HTTP request* @param response current HTTP response* @param handler chosen handler to execute, for type and/or instance evaluation* @return {@code true} if the execution chain should proceed with the* next interceptor or the handler itself. Else, DispatcherServlet assumes* that this interceptor has already dealt with the response itself.* @throws Exception in case of errors*/default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {return true;}/*** Intercept the execution of a handler. Called after HandlerAdapter actually* invoked the handler, but before the DispatcherServlet renders the view.* Can expose additional model objects to the view via the given ModelAndView.* <p>DispatcherServlet processes a handler in an execution chain, consisting* of any number of interceptors, with the handler itself at the end.* With this method, each interceptor can post-process an execution,* getting applied in inverse order of the execution chain.* <p><strong>Note:</strong> special considerations apply for asynchronous* request processing. For more details see* {@link org.springframework.web.servlet.AsyncHandlerInterceptor}.* <p>The default implementation is empty.* @param request current HTTP request* @param response current HTTP response* @param handler the handler (or {@link HandlerMethod}) that started asynchronous* execution, for type and/or instance examination* @param modelAndView the {@code ModelAndView} that the handler returned* (can also be {@code null})* @throws Exception in case of errors*/default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,@Nullable ModelAndView modelAndView) throws Exception {}/*** Callback after completion of request processing, that is, after rendering* the view. Will be called on any outcome of handler execution, thus allows* for proper resource cleanup.* <p>Note: Will only be called if this interceptor's {@code preHandle}* method has successfully completed and returned {@code true}!* <p>As with the {@code postHandle} method, the method will be invoked on each* interceptor in the chain in reverse order, so the first interceptor will be* the last to be invoked.* <p><strong>Note:</strong> special considerations apply for asynchronous* request processing. For more details see* {@link org.springframework.web.servlet.AsyncHandlerInterceptor}.* <p>The default implementation is empty.* @param request current HTTP request* @param response current HTTP response* @param handler the handler (or {@link HandlerMethod}) that started asynchronous* execution, for type and/or instance examination* @param ex any exception thrown on handler execution, if any; this does not* include exceptions that have been handled through an exception resolver* @throws Exception in case of errors*/default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,@Nullable Exception ex) throws Exception {}}

SpringMVC拦截器与Filter过滤器相关推荐

  1. JAVA incept_java 过滤器(Filter)与springMVC 拦截器(interceptor)的实现案例

    java 过滤器Filter: package com.sun.test.aircraft.filter; import javax.servlet.*; import java.io.IOExcep ...

  2. SpringMVC→拦截器、SpringMVC拦截器实现、多个拦截器工作原理、拦截器使用场景、拦截器Interceptor与过滤器Filter区别

    拦截器 拦截器实现 多个拦截器工作原理 拦截器使用场景 请求编码设置及请求登录Session校验 使用时间段设置 拦截器Interceptor与过滤器Filter区别

  3. Java Servlet 过滤器与 springmvc 拦截器的区别?

    前言:在工作中,遇到需要记录日志的情况,不知道该选择过滤器还是拦截器,故总结了一下. servlet 过滤器 定义 java过滤器能够对目标资源的请求和响应进行截取.过滤器的工作方式分为四种 应用场景 ...

  4. 总结 拦截器(Interceptor) 和 过滤器(Filter)的区别

    一.前言 拦截器(Interceptor) 和 过滤器(Filter)的区别是面试中常问的问题,也是开发中容易被大家混淆的问题,在此总结下,希望对大家有所帮助. 二.Filter 介绍 2.1.概念 ...

  5. Spring+SpringMVC+MyBatis深入学习及搭建(十七)——SpringMVC拦截器

    转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7098753.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十六)--S ...

  6. 在拦截器里放入参数 controller_干货|SpringMVC拦截器的使用详解

    一.拦截器简介 Spring MVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理. 常见应用场景 1.日志记录:记录请求信息的日志,以便进行信息监控.信 ...

  7. 跨域请求/SpringMVC拦截器

    <!-- 开启允许跨域 --> <mvc:cors> <mvc:mapping path="/**"/> </mvc:cors> S ...

  8. SpringMVC拦截器Interceptor

    SpringMVC拦截器(Interceptor)实现对每一个请求处理前后进行相关的业务处理,类似与servlet中的Filter. SpringMVC 中的Interceptor 拦截请求是通过Ha ...

  9. SpringMVC与JSON传值,取值,使用SpringMVC实现文件的上传与下载,SpringMVC拦截器

    一. JSON 1.1 什么是JSON 在实际开发中,通常需要和别的系统交换数据,数据交换的格式通常有XML和JSON等: JSON(JavaScript Object Notation:JavaSc ...

最新文章

  1. 如何打造项目级硬核简历,成为一名合格的大厂工程师(必看)
  2. 幼儿园python_[Python]猜数字游戏AI版的实现(幼儿园智商AI)
  3. 【Flutter】Flutter 启动白屏问题 ( 问题描述 | 在 launch_background.xml 中设置启动过渡 UI )
  4. 【推荐系统】双塔模型中的负采样
  5. Java @Transient 注解使用
  6. Linux内核热补丁方案对比
  7. 《DSP using MATLAB》Problem 6.6
  8. python代码的层次结构_Python的object和type理解及主要对象层次结构
  9. opencv基础:相机参数标定(camera calibration)及标定结果如何使用
  10. 人工智能产品经理最佳实践
  11. 大华平台linux密码,大华指纹锁管理员密码忘了
  12. ChineseBERT: Chinese Pretraining Enhanced by Glyph and Pinyin Information
  13. 电脑端哔哩哔哩视频下载
  14. Android的在线考试app
  15. 你的快递“动”了吗,快递受阻,缺的不止快递小哥
  16. 怎么把html转成mp4,怎么把其他视频格式转成常用的mp4形式?
  17. JS实现邮箱提示补全效果
  18. uniApp开发小程序(7)使用mescroll配置上啦下拉的样式,以及分类页面的配置
  19. 牛客网JS(nodeJS)单行、多行输入和输出
  20. 【 天梯赛L2-028 秀恩爱分得快】

热门文章

  1. Android 文件下载,根据url获取真正的文件名和后缀名(包括重定向的url)
  2. 计算机信息安全培训计划,年度信息安全培训计划.doc
  3. Visual Studio 2019 中使用 DotNetBar
  4. 微信页面使用的日期插件
  5. 为什么次对角线元素均不为零的三对角矩阵为不可约矩阵
  6. 过程能力分析02—Box-Cox变换:非正态数据能力分析的处理办法
  7. Visual Studio Code 快捷键 Mac 版
  8. 蜗牛也能爬动的JAVA学习路线,希望能帮助毕业迷茫的你
  9. 点云处理需要多大的计算机,一种点云数据处理方法、装置、计算机设备和存储介质与流程...
  10. euraka注册中心配置步骤(Maven工程导入)