title: How to get the XML from POST request and modify it in Servlet Filter?
body: <p>I am currently working on a requirement where I need to get the XML (from POST request) in the servlet filter before the request reaches to the Spring controller and then I need to process the XML (cut off some empty nodes/elements) in the filter and then the call should proceed further.</p>
  
  <p>I tried the below code (attached only snippet) and I was able to get the request body (XML) and able to set the modified response.</p>
  
  <pre><code>    HttpServletRequest httpRequest = (HttpServletRequest) request;
      HttpServletResponse httpResponse = (HttpServletResponse) response;
      if (httpRequest.getMethod().equalsIgnoreCase("POST")) {
        extractDataFromRequest(httpRequest);
        httpResponse.getWriter().write("&lt;root&gt;&lt;root&gt;");
      }
      chain.doFilter(request, wrappedResponse);
  
     public static String extractDataFromRequest(HttpServletRequest request) throws IOException {
  
      String line;
      StringBuilder builder = new StringBuilder();
      BufferedReader reader = request.getReader();
      while ((line = reader.readLine()) != null) {
        builder.append(line);
      }
      return builder.toString();
    }
  </code></pre>
  
  <p>However, spring failed with the following exception.</p>
  
  <pre><code>Severe: java.lang.IllegalStateException: PWC3997: getReader() has already been called for this request
      at org.apache.catalina.connector.Request.getInputStream(Request.java:1178)
      at org.apache.catalina.connector.RequestFacade.getInputStream(RequestFacade.java:407)
      at org.springframework.http.server.ServletServerHttpRequest.getBody(ServletServerHttpRequest.java:165)
      at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:120)
      at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:100)
  </code></pre>
  
  <p>I am looking for a concrete implementation for this requirement from experts.</p>