Is Spring HandlerInterceptorAdapter postHandle guaranteed?

后端 未结 1 850
小鲜肉
小鲜肉 2020-12-19 06:35

I currently have two interceptors that handle a similar function. I\'d like to merge these.

One interceptor is an access request logger, that shows the logged in use

相关标签:
1条回答
  • 2020-12-19 06:39

    You can consider merging the logic inside the afterCompletion which will be called even in the case when a handler method throws an exception. A good online example

    public class RequestProcessingTimeInterceptor extends HandlerInterceptorAdapter {
    
        private static final Logger logger = LoggerFactory
                .getLogger(RequestProcessingTimeInterceptor.class);
    
        @Override
        public boolean preHandle(HttpServletRequest request,
                HttpServletResponse response, Object handler) throws Exception {
            long startTime = System.currentTimeMillis();
            logger.info("Request URL::" + request.getRequestURL().toString()
                    + ":: Start Time=" + System.currentTimeMillis());
            request.setAttribute("startTime", startTime);
            //if returned false, we need to make sure 'response' is sent
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request,
                HttpServletResponse response, Object handler,
                ModelAndView modelAndView) throws Exception {
            System.out.println("Request URL::" + request.getRequestURL().toString()
                    + " Sent to Handler :: Current Time=" + System.currentTimeMillis());
            //we can add attributes in the modelAndView and use that in the view page
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request,
                HttpServletResponse response, Object handler, Exception ex)
                throws Exception {
            long startTime = (Long) request.getAttribute("startTime");
            logger.info("Request URL::" + request.getRequestURL().toString()
                    + ":: End Time=" + System.currentTimeMillis());
            logger.info("Request URL::" + request.getRequestURL().toString()
                    + ":: Time Taken=" + (System.currentTimeMillis() - startTime));
        }
     }
    
    0 讨论(0)
提交回复
热议问题