spring 如何在RequestDispatcher转发后获取请求和响应字符串

mwg9r5ms  于 2023-04-28  发布在  Spring
关注(0)|答案(1)|浏览(149)

在我的Springboot应用程序中,我使用RequestDispatcher forward将请求和响应发送到远程服务。现在我需要得到responserequest作为字符串来记录到数据库。requestresponse都包含JSON数据。

  1. RequestDispatcher requestDispatcher = request.getRequestDispatcher(configAPI.getUserByPhoneUrl());
  2. requestDispatcher.forward(request, response);

RequestDispatcher将就地修改响应。因此,在forward()函数之后,我无法从requestDispatcher.forward(request, response)创建的响应中获取json。

  1. @RequestMapping(value = "/getUserByPhone", method = {RequestMethod.GET}, produces = "application/json;charset=utf-8")
  2. public void getUserbyIsdn(HttpServletRequest request, HttpServletResponse response) {
  3. // Forward the request to the remote service
  4. RequestDispatcher requestDispatcher = request.getRequestDispatcher(configAPI.getUserByPhoneUrl());
  5. requestDispatcher.forward(request, response);
  6. // response now has result from remote service
  7. // TODO: print out json in response here
  8. }

有没有关于如何获得响应作为json的想法?
我尝试使用HttpServletResponseWrapper访问响应,但无法访问。使用HttpServletResponseWrapper的示例代码:

  1. HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request);
  2. HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
  3. // Forward the request to the remote service
  4. request.getRequestDispatcher(configAPI.getUserByPhoneUrl()).forward(requestWrapper, responseWrapper);

但由于未设置ApplicationContext请求,因此导致NullPointerException。

0yg35tkg

0yg35tkg1#

经过一些尝试,我能够使用ContentCachingRequestWrapperContentCachingResponseWrapper获得响应并请求json字符串。控制器现在变成这样:

  1. @RequestMapping(value = "/getUserByPhone", method = {RequestMethod.GET}, produces = "application/json;charset=utf-8")
  2. public void getUserbyIsdn(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
  3. ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
  4. ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
  5. requestWrapper.getRequestDispatcher(configAPI.getApi_getUserbyIsdn_user()).forward(requestWrapper, responseWrapper);
  6. // do what ever you want here with response and request
  7. apiLogService.addApiLog(requestWrapper, responseWrapper, "getUserByIsdn", timer);
  8. // have to has this to return original response of other service
  9. responseWrapper.copyBodyToResponse();
  10. }

函数addApiLog

  1. public void addApiLog(ContentCachingRequestWrapper request, ContentCachingResponseWrapper response) {
  2. String requestJson = IOUtils.toString(request.getContentAsByteArray());
  3. String responseJson = IOUtils.toString(response.getContentAsByteArray());
  4. // handle json String using JSONObject or GSON as needed
  5. }
展开查看全部

相关问题