Spring HandlerInterceptorAdapter postHandle 有保障吗?

Is Spring HandlerInterceptorAdapter postHandle guaranteed?

我目前有两个处理类似功能的拦截器。我想合并这些。

一个拦截器是一个访问请求记录器,显示登录用户、会话 ID 和请求 URL。

另一个拦截器是进程时间记录器。

访问记录器为了记录所有必须记录的内容,将请求记录在preHandle 方法中。这个想法是,无论之后发生什么(即异常),确切的访问请求都会在那里。

然而,进程时间记录器由于其性质,必须在 postHandle 方法中进行记录。

为了合并此功能,我必须将所有内容移动到一个 postHandle 方法中。但是,如果某处发生异常,尤其是应用程序代码中(尚未)正确处理的异常,我似乎可能会丢失一些日志记录。

这些注意事项是否有任何保证或描述?

您可以考虑合并 afterCompletion 中的逻辑,即使在处理程序方法抛出异常的情况下也会调用该逻辑。不错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));
    }
 }