gpt4 book ai didi

spring-mvc - ContentCachingResponseWrapper 生成空响应

转载 作者:行者123 更新时间:2023-12-02 23:55:09 32 4
gpt4 key购买 nike

我正在尝试在 Spring MVC 应用程序中实现用于记录请求和响应的过滤器。我使用以下代码:

@Component
public class LoggingFilter extends OncePerRequestFilter {

private static final Logger LOGGER = LoggerFactory.getLogger(LoggingFilter.class);

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);

LOGGER.debug(REQUEST_MESSAGE_FORMAT, requestWrapper.getRequestURI(), requestWrapper.getMethod(), requestWrapper.getContentType(),
new ServletServerHttpRequest(requestWrapper).getHeaders(), IOUtils.toString(requestWrapper.getInputStream(), UTF_8));

filterChain.doFilter(requestWrapper, responseWrapper);

LOGGER.debug(RESPONSE_MESSAGE_FORMAT, responseWrapper.getStatus(), responseWrapper.getContentType(),
new ServletServerHttpResponse(responseWrapper).getHeaders(), IOUtils.toString(responseWrapper.getContentInputStream(), UTF_8));
}
}

因此,我收到了我的请求并按预期记录了响应。以下是日志:

2016-10-08 19:10:11.212 DEBUG 11072 --- [qtp108982313-19] by.kolodyuk.logging.LoggingFilter
----------------------------
ID: 1
URI: /resources/1
Http-Method: GET
Content-Type: null
Headers: {User-Agent=[curl/7.41.0], Accept=[*/*], Host=[localhost:9015]}
Body:
--------------------------------------
2016-10-08 19:10:11.277 DEBUG 11072 --- [qtp108982313-19] by.kolodyuk.logging.LoggingFilter
----------------------------
ID: 1
Response-Code: 200
Content-Type: application/json;charset=UTF-8
Headers: {}
Body: {"id":"1"}
--------------------------------------

但是,返回的是空响应。以下是 curl 的输出:

$ curl http://localhost:9015/resources/1 --verbose
* Trying ::1...
* Connected to localhost (::1) port 9015 (#0)
> GET /resources/1 HTTP/1.1
> User-Agent: curl/7.41.0
> Host: localhost:9015
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Sat, 08 Oct 2016 17:10:11 GMT
< Content-Type: application/json;charset=UTF-8
< Content-Length: 0
<
* Connection #0 to host localhost left intact

有什么想法吗?

谢谢

最佳答案

经过几个小时的努力,我终于找到了解决方案。

简而言之,应在过滤器方法的末尾调用 ContentCachingResponseWrapper.copyBodyToResponse()

ContentCachingResponseWrapper 通过从响应输出流读取响应正文来缓存响应正文。因此,流变空了。要将响应写回输出流,应使用 ContentCachingResponseWrapper.copyBodyToResponse()

关于spring-mvc - ContentCachingResponseWrapper 生成空响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39935190/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com