【问题标题】:How to access HttpServletResponse object in @Around advice如何在@Around 建议中访问 HttpServletResponse 对象
【发布时间】:2015-05-24 05:59:57
【问题描述】:

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

    @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,因此我可以输出我的返回码。我可以肯定地在控制器中处理它,但有兴趣将这一切都保留在方面。

【问题讨论】:

    标签: spring servlets model-view-controller aop aspectj


    【解决方案1】:

    据我所知,当控制器返回时,响应尚未形成。这将在响应形成之前进一步交给 spring 的视图解析器 api。 如果您的意图只是记录 appserver 处理请求所花费的时间,您可能需要查看“javax.servlet.Filter”实现。它为您提供所有请求/响应 api 的处理,它可能是要执行的第一件事和最后一件事,具体取决于您在 web.xml 中配置过滤器链的方式。 此外,控制器周围的方面将不包括执行 jsp 所花费的时间。在控制器返回后,一些标签处理程序可能会为您的处理增加大量时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-12
      • 1970-01-01
      相关资源
      最近更新 更多