将请求和响应记录到Rest控制器方法中

时间:2019-05-23 11:01:27

标签: java spring spring-boot

我想实现将所有内容记录到数据库的过滤器。我尝试了此过滤器:

@Component
public class HttpLoggingFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(HttpLoggingFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        ResettableStreamHttpServletRequest wrappedRequest = new ResettableStreamHttpServletRequest(
                (HttpServletRequest) request);
        wrappedRequest.getInputStream().read();
        String body = IOUtils.toString(wrappedRequest.getReader());
        wrappedRequest.resetInputStream();
        // ......

        chain.doFilter(wrappedRequest, response);
    }

端点暗示:

@RestController()
public class HomeController {

    @PostMapping(value = "/v1", consumes = { MediaType.APPLICATION_XML_VALUE,
      MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_XML_VALUE,
          MediaType.APPLICATION_JSON_VALUE })
  public Response handleMessage(@RequestBody Transaction transaction, HttpServletRequest request, org.zalando.logbook.HttpRequest requestv, HttpServletResponse response) throws Exception {

       // Get here request and response and log it into DB
     } 
}

如何调用HttpLoggingFilter到Java方法handleMessage中并以主体String的形式获取请求?也许我可以提供服务并注入它?您能给我一些建议,以评估代码吗?

0 个答案:

没有答案