问题描述
我有一个 Spring Boot 应用程序.现在我需要在拦截器中读取请求和响应.我使用 HttpServletRequestWrapper
替换 DispatcherServlet
I have a spring boot application. And now I need to read request and response in interceptor.I use a HttpServletRequestWrapper
replace the request in DispatcherServlet
@Component("dispatcherServlet")
public class FofDisPatcherServlet extends DispatcherServlet {
@Override
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
MultiReadHttpServletRequest requestWrapper = null;
try {
requestWrapper = new MultiReadHttpServletRequest(request);
super.doDispatch(requestWrapper, response);
} catch (Exception e) {
super.doDispatch(request,response);
}
}
}
在我的拦截器中,我可以读取请求正文.但是当我想读取响应正文时,它不起作用.当我替换 CustomerDispatcherServlet
中的响应时,我没有任何响应.我尝试过 ContentCachingResponseWrapper
,但我得到带有"的payload.
And in my interceptor , I can read the request body. But when I want to read the response body, it doesn't works.when I replace the response in the CustomerDispatcherServlet
I got nothing response.I have tried ContentCachingResponseWrapper
, but I got the payload with "".
这是一个老问题.我搜索了一些问题,但没有找到合适的解决方案.
It's a old question.and I have search some questions but didn't find a suitable solution.
我知道我可以用AOP
解决这个问题.但是我想知道我在拦截器中怎么做?
I know I can solve the problem with AOP
.But I want to know how can I do it in the interceptor?
这是我的拦截器代码
public class CustomerInterceptor extends HandlerInterceptorAdapter{
@Override
public void postHandle(...){
MultiReadHttpServletRequest req = (MultiReadHttpServletRequest) request;
ContentCachingResponseWrapper res = new ContentCachingResponseWrapper(response);
Byte[] body = res. getContentAsByteArray();
...
}
}
我得到的身体是 [].
the body I got is [].
推荐答案
几天后,我找到了答案.在 CustomerDispatcherServlet
我应该添加 responseWrapper.copyBodyToResponse()
After few days .I find the answer.In the CustomerDispatcherServlet
I should add responseWrapper.copyBodyToResponse()
CustomerDIspatcherServlet
像这样:
@Component("dispatcherServlet")
public class FofDisPatcherServlet extends DispatcherServlet {
@Override
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
MultiReadHttpServletRequest requestWrapper = null;
try {
requestWrapper = new MultiReadHttpServletRequest(request);
if (!(response instanceof ContentCachingResponseWrapper)) {
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
super.doDispatch(requestWrapper, responseWrapper);
responseWrapper.copyBodyToResponse();
}else {
super.doDispatch(requestWrapper, response);
}
} catch (Exception e) {
super.doDispatch(request, response);
}
}
}
这篇关于如何在拦截器中读取httpServletResponse?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!