interceptor(拦截器)

interceptor(拦截器)

拦截器,顾名思义,他的作用就是拦截,这个要和过滤器区分开,过滤器依赖serverlet容器,获取request和response处理,是基于函数回调,简单说就是“去取你想取的”,拦截器是通过java反射机制,动态代理来拦截web请求,是“拒你想拒绝的”,他只拦截web请求,但不拦截静态资源,Struts2里面就是将拦截器串联,实现对请求的处理,下面以spring 的拦截器为例,写个demo


/**

* @author [email protected]

* @date 2019-04-13 14:50

*/

@Component

public class MyInterceptor implements HandlerInterceptor {


    @Override

    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object hanlder) {

        out.println("拦截器.preHandle 开始执行。。。");

        out.println(hanlder.getClass().getSimpleName());

        out.println(((HandlerMethod) hanlder).getBean().getClass().getName());

        httpServletRequest.setAttribute("start", currentTimeMillis());

        return true;

    }


    @Override

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object hanlder, ModelAndView modelAndView) {

        out.println("拦截器.postHandle 开始执行。。。");

        long start = (long) httpServletRequest.getAttribute("start");

        out.println("postHandle执行时间为:" + (currentTimeMillis() - start));


    }


    @Override

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object hanlder, Exception e) {

        //会打印两次 spring里面的basic error 也会被拦截

        out.println("拦截器.afterCompletion 开始执行。。。");

        long start = (long) httpServletRequest.getAttribute("start");

        out.println("afterCompletion执行时间为:" + (currentTimeMillis() - start));

        out.println("\n ex is :" + e+"\n");

    }

}

你可能感兴趣的:(interceptor(拦截器))