无法读取HttpServletRequest有效负载

时间:2019-05-23 09:28:41

标签: java spring spring-boot spring-rest

我想创建过滤器,该过滤器打印请求和响应有效负载。我尝试过:

@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 {

    }
}

但是我收到所有REST API请求的空响应。实施此操作的适当理由是什么?

1 个答案:

答案 0 :(得分:1)

您需要使您的过滤器执行某些操作,至少要继续进行链中的调用,例如...

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

编辑:

(请参阅评论)

请注意,如果您执行这样的操作...

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    BufferedReader reader = new BufferedReader(new InputStreamReader(httpServletRequest.getInputStream()));

    String line = reader.readLine();

    while(line != null) {
        System.out.println(line);
        line = reader.readLine();
    }

    chain.doFilter(request, response);
}

...那么您将消耗掉实际的请求正文,任何下游过滤器(或实际的端点)将无法读取它。如果您要这样做,您将需要执行类似https://gist.github.com/calo81/2071634的操作。