如何在@Around 建议中访问 HttpServletResponse 对象

How to access HttpServletResponse object in @Around advice

我想在日志记录方面捕获 httpResponse 对象,以便我可以为我的控制器方法集中记录 http return 代码。例如类似于:

    @Around("execution(* ..*Controller.*(..))")
    public Object handleLogging(ProceedingJoinPoint pjp) throws Throwable {

        // start stopwatch
        long startTime = System.currentTimeMillis();

        // HttpServletRequest works no problem 
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        logger.info("this was the request url", request.getRequestURI());

        // proceed with method
        try {
            retVal = pjp.proceed();
        }
        finally{
            // stop stopwatch
            long endTime = System.currentTimeMillis();
            long duration = endTime-startTime;

            // how do I get the response?
            // this doesn't seem to work, response is null..
            ServletWebRequest servletWebRequest=new ServletWebRequest(request);
HttpServletResponse response=servletWebRequest.getResponse();


            logger.info(appendEntries(securityAuditParameters),
                    "Method={} executionSuccess={} executionTime={}", pjp.getSignature(), response.getStatus(), duration);

        }
        return retVal;
    }

我一直无法弄清楚如何获取 HttpServletResponse 以便输出我的 return 代码。我肯定可以在控制器中处理它,但有兴趣将这一切都保留在方面。

据我所知,返回控制器时还没有形成响应。这将在响应形成之前进一步移交给spring的视图解析器api。 如果您的目的只是记录应用服务器为请求提供服务所花费的时间,您可能需要查看“javax.servlet.Filter”实现。它为您提供了所有 request/response api 的句柄,它可以是第一个也是最后一个要执行的事情,具体取决于您在 web.xml 中配置过滤器链的方式。 此外,控制器周围的方面将不包括执行 jsp 所花费的时间。在控制器返回后,一些标记处理程序可能会为您的处理增加相当多的时间。