码迷,mamicode.com
首页 > 其他好文 > 详细

拦截器

时间:2019-12-19 17:38:09      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:boolean   dap   over   进入   str   autowire   gis   sys   obj   

创建拦截器

1 实现 HandlerInterceptor 创建拦截器

@Component
public class TimeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("startTime", new Date().getTime());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Long start = (Long) request.getAttribute("startTime");
        System.out.println("time interceptor 耗时:"+ (new Date().getTime() - start));

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Long start = (Long) request.getAttribute("startTime");
        System.out.println("time interceptor 耗时:"+ (new Date().getTime() - start));
        System.out.println("ex is "+ex);
    }

}

2 配置类中 继承 WebMvcConfigurerAdapter 注册拦截器

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    
    @SuppressWarnings("unused")
    @Autowired
    private TimeInterceptor timeInterceptor;
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(timeInterceptor);
    }

}

preHandle、postHandle与afterCompletion

preHandle

调用时间:Controller方法处理之前

执行顺序:链式Intercepter情况下,Intercepter按照声明的顺序一个接一个执行

若返回false,则中断执行,注意:不会进入afterCompletion

postHandle

调用前提:preHandle返回true

调用时间:Controller方法处理完之后,DispatcherServlet进行视图的渲染之前,也就是说在这个方法中你可以对ModelAndView进行操作

执行顺序:链式Intercepter情况下,Intercepter按照声明的顺序倒着执行。

备注:postHandle虽然post打头,但post、get方法都能处理

afterCompletion

调用前提:preHandle返回true

调用时间:DispatcherServlet进行视图的渲染之后

多用于清理资源

拦截器

标签:boolean   dap   over   进入   str   autowire   gis   sys   obj   

原文地址:https://www.cnblogs.com/tekken-wang/p/12069038.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!