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

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

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

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

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

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

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

HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request);
            HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);

            // Forward the request to the remote service
            request.getRequestDispatcher(configAPI.getUserByPhoneUrl()).forward(requestWrapper, responseWrapper);

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

0yg35tkg

0yg35tkg1#

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

@RequestMapping(value = "/getUserByPhone", method = {RequestMethod.GET}, produces = "application/json;charset=utf-8")
    public void getUserbyIsdn(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
        requestWrapper.getRequestDispatcher(configAPI.getApi_getUserbyIsdn_user()).forward(requestWrapper, responseWrapper);
        // do what ever you want here with response and request
        apiLogService.addApiLog(requestWrapper, responseWrapper, "getUserByIsdn", timer);

        // have to has this to return original response of other service
        responseWrapper.copyBodyToResponse();
    }

函数addApiLog

public void addApiLog(ContentCachingRequestWrapper request, ContentCachingResponseWrapper response) {
    String requestJson = IOUtils.toString(request.getContentAsByteArray());
    String responseJson = IOUtils.toString(response.getContentAsByteArray());
    // handle json String using JSONObject or GSON as needed
}

相关问题