当前位置 > it书童 > java > 正文

SpringMvc 拦截器详解

java it书童 2020-11-16 21:07:45 0赞 0踩 417阅读 0评论

拦截器各个方法的执行时机

public class MyInterceptor1 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器1 - 前置方法执行了...");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器1 - 后置方法执行了...");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("拦截器1 - 最后方法执行了...");
    }
}

可以在拦截器中设置跳转,如:

request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);

配置多个拦截器

有多个拦截器时,注意这些拦截器的执行顺序,每个拦截器都需要独立配置

<mvc:interceptors>
    <!--第1个拦截器-->
    <mvc:interceptor>
        <mvc:mapping path="/user/*"/>
        <bean class="com.itshutong.interceptor.MyInterceptor1" />
    </mvc:interceptor>

    <!--第2个拦截器-->
    <mvc:interceptor>
        <mvc:mapping path="/user/*"/>
        <bean class="com.itshutong.interceptor.MyInterceptor2" />
    </mvc:interceptor>
</mvc:interceptors>

源码 javaDemo 182961f

关于我
一个文科出身的程序员,追求做个有趣的人,传播有价值的知识,微信公众号主要分享读书思考心得,不会有代码类文章,非程序员的同学请放心订阅
转载须注明出处:https://www.itshutong.com/articles/822