I have a spring app that has some servlets inside it. The requests are all wired up and working with like ServletComponentScan but in the Servlet, when it tries to use the "getInputStream" or whatever, it returns no data. I am guessing that this is because Spring reads the body first and that data can only be read once. Is there a way to make this work properly?
@WebServlet(urlPatterns={"/servlet"})
public class ServletController extends HttpServlet {
private static final Logger logger = LoggerFactory.getLogger(ServletController.class);
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
String bodyData = extractBody(req);
out.println("BodyData: " + bodyData);
}
public static String extractBody(HttpServletRequest request) {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader reader = null;
try {
InputStreamReader isr = new InputStreamReader(request.getInputStream());
reader = new BufferedReader(isr);
int i;
while ((i = reader.read()) != -1) {
sb.appendCodePoint(i);
}
} catch (Exception e) {
logger.error("Failed to read from servletRequest with content-length: {}", request.getHeader("Content-Length"));
e.printStackTrace();
}
return sb.toString();
}
}
Above is an example that when on it's own in tomcat or whatever, it's fine. When it is in a Spring related app it doesn't work.
Spring
$ curl -X POST -d'{}' http://localhost:8080/servlet
BodyData:
Plain Servlet (built into "plainservlet.war" and deployed to tomcat)
# curl -X POST -d'{}' http://localhost:8081/plainservlet/servlet
BodyData: {}