SpringMVC框架学习笔记(6)——拦截器

SpringMVC拦截器需要实现接口HandlerInterceptor

有3个方法,分别在请求处理前、请求处理后和在DispatcherServlet处理后执行

实现代码:

package interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class MyInterceptor implements HandlerInterceptor {

    //在DispatcherServlet处理后执行,清理工作
    @Override
    public void afterCompletion(HttpServletRequest arg0,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {

    }

    //在请求处理方法后执行
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
        System.out.println("-----处理后-----");

    }

    //在请求处理方法前执行
    //返回true执行下一个拦截器,返回false不执行
    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2) throws Exception {
        System.out.println("-----处理前-----");
        return true;
    }

}
View Code

如何将拦截器配置到对应请求上

首先引入SpringMVC命名空间

xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd"

配置拦截器

<mvc:interceptors>
   <mvc:interceptor>
       <mvc:mapping path="/**"/>
       <bean class="interceptor.MyInterceptor"></bean>
   </mvc:interceptor>
</mvc:interceptors>

interceptors表示多个拦截器

interceptor表示单个拦截器

/**表示根路径及根路径下所有子路径

/test/*表示test的一级子路径比如/test/test

/test/**表示test的一级子路径及一级子路径下的所有子路径

bean指向的是配置的拦截器

bean直接写在interceptors里表示通用拦截器

原文地址:https://www.cnblogs.com/huangjian2/p/6774499.html