I have a servlet Filter that reads the request parameter/header and performs some logic before calling chain.doFilter(req, resp). The servlet that responds to this call further down the chain has an empty stream because the request stream was already read in the filter. To fix this, I created a ServletRequestWrapper, read the input stream and cached the body which is eventually streamed via the overriden getInputStream method.
chain.doFilter(wrapper, resp) will now carry the payload and all is well and fixes my problem.
However, my question is on performance. Creating a wrapper just to cache my request body is essentially reading the input stream once and the servlet eventually reads the stream again, resulting in a double read of the stream. This might be OK for POST requests but a PUT request carrying a really big file's payload might not be ideal to go through this double read.
Any thoughts or alternative approaches?
Here's the code snippets of the filter and servlet.
//The sample Filter code
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain){
HttpServletRequest req = (HttpServletRequest)request;
if(verifySomething(req.getParameter('someParam'))){
chain.doFilter(req, resp);
}
}
//Servlet code
protected void doPut(HttpServletRequest req, HttpServletResponse resp){
writeFile(req.getInputStream()); //Stream is empty here
}
Thanks.