1

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.

Vik
  • 55
  • 7
  • Can you post the code so we can tell if there is any alternative ? – Vasu Nov 02 '16 at 20:42
  • I've added snippets to the original post. – Vik Nov 03 '16 at 14:11
  • --- the servlet eventually reads the stream again, resulting in a double read of the stream. -- the stream can be read only one! – LHA Nov 03 '16 at 14:22
  • I did fix it by writing a ServletRequestWrapper that stores the stream data. So my question was is it a good practice to store the request stream in a wrapper which means an extra read of the stream and might not be efficient if the stream is carrying lot of data. – Vik Nov 03 '16 at 14:26
  • 1
    I think I got a pretty good response to my issue with this post (not exactly related) http://stackoverflow.com/questions/34804205/how-can-i-read-request-body-multiple-times-in-spring-handlermethodargumentresol – Vik Nov 03 '16 at 20:41

0 Answers0