Skip to content

五、拦截器

一、拦截器(interceptor)的作用

提示

Spring MVC 的拦截器类似于Servlet 开发中的过滤器 Filter,用于对处理器进行预处理后处理

将拦截器按一定的顺序联结成一条链,这条链称为拦截器链(Interceptor Chain)。在访问被拦截的方法或字段时,拦截器链中的拦截器就会按其之前定义的顺序被调用。拦截器也是AOP思想的具体实现。

1、拦截器和过滤器区别

区别过滤器(Filter)拦截器(Interceptor)
使用范围是 servlet 规范中的一部分,任何Java Web 工程都可以使用是 SpringMVC 框架自己的,只有使用了SpringMVC 框架的工程才能用
拦截范围在 url-pattern 中配置了/*之后,可以对所有要访问的资源拦截使用<mvc:interceptor><mvc:mapping path="" />中配置了/**之后,也可以多所有资源进行拦截,但是可以通过<mvc:exclude-mapping path=""/>标签排除不需要拦截的资源

二、拦截器方法说明

方法名说明
preHandle()方法将在请求处理之前进行调用,该方法的返回值是布尔值Boolean类型的,当它返回为false时,表示请求结束,后续的Interceptor和Controller都不会再执行;当返回值为true 时就会继续调用下一个interceptor的preHandle方法
postHandle()该方法是在当前请求进行处理之后被调用,前提是preHandle方法的返回值为true 时才能被调用,且它会在DispatcherServlet进行视图返回渲染之前被调用,所以我们可以在这个方法中对Controller处理之后的ModelAndView对象进行操作
afterCompletion()该方法将在整个请求结束之后,也就是在DispatcherServlet染了对应的视图之后执行,前提是preHandle方法的返回值为true时才能被调用

三、拦截器的使用

java
public class TestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("运行函数前...");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("运行函数快结束...");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("运行函数结束了...");
    }
}
xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
">

    <mvc:annotation-driven/>

    <context:component-scan base-package="com.hdq.controller"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <mvc:default-servlet-handler/>

    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.hdq.interceptor.TestInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

</beans>