欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring MVC的拦截器

程序员文章站 2022-07-09 18:18:40
...

1.定义自己的spring mvc拦截器需要实现HandlerInterceptor 接口或者继承HandlerInterceptorAdapter

2.boolean preHandle()方法在controller被调用之前调用;

3.void postHandle()方法在controller被调用之后调用,可在modelandview中加入数据,比如当前时间;

4.void afterCompletion()在呈现视图之后调用,可用于清理资源等;

5.当设置多个拦截器时,先按顺序调用preHandle方法,然后逆序调用每个拦截器的postHandle和afterCompletion方法


Spring MVC的拦截器

6.拦截器代码

public class MyInterceptor1 extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("-------preHandle1-------");
        return true;//如果返回false,则不再调用之后的方法
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("-------postHandle1-------");
        if(modelAndView != null){  //加入当前时间
            modelAndView.addObject("now", new Date());
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("-------afterCompletion1-------");
    }
    

}
public class MyInterceptor2 extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("-------preHandle2-------");
        return true;//如果返回false,则不再调用之后的方法
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("-------postHandle2-------");
        if(modelAndView != null){  //加入当前时间
            modelAndView.addObject("now", new Date());
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("-------afterCompletion2-------");
    }
    

}

 7.配置

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**"/>
        <bean class="com.nexusy.web.interceptor.MyInterceptor1" />
    </mvc:interceptor>
    <mvc:interceptor>
        <mvc:mapping path="/**"/>
        <bean class="com.nexusy.web.interceptor.MyInterceptor2" />
    </mvc:interceptor>
</mvc:interceptors>

8.输出

-------preHandle1-------
-------preHandle2-------
-------controller-------
-------postHandle2-------
-------postHandle1-------
-------afterCompletion2-------
-------afterCompletion1-------