Accessing HTTP Servlet Request Parameters without Consumption
Problem:
When accessing multiple HTTP request parameters within a Servlet filter, the initial parameter access consumes the parameters, making them unavailable for subsequent use. This issue particularly arises with POST requests where parameters reside in the request body.
Solution:
To access parameters without consuming them, you can extend HttpServletRequestWrapper and implement custom methods to cache the input stream:
public class MultiReadHttpServletRequest extends HttpServletRequestWrapper { private ByteArrayOutputStream cachedBytes; public MultiReadHttpServletRequest(HttpServletRequest request) { super(request); } @Override public ServletInputStream getInputStream() throws IOException { if (cachedBytes == null) cacheInputStream(); return new CachedServletInputStream(cachedBytes.toByteArray()); } @Override public BufferedReader getReader() throws IOException{ return new BufferedReader(new InputStreamReader(getInputStream())); } private void cacheInputStream() throws IOException { cachedBytes = new ByteArrayOutputStream(); IOUtils.copy(super.getInputStream(), cachedBytes); } private static class CachedServletInputStream extends ServletInputStream { private final ByteArrayInputStream buffer; public CachedServletInputStream(byte[] contents) { this.buffer = new ByteArrayInputStream(contents); } @Override public int read() { return buffer.read(); } // ... Implementation for newer versions of ServletInputStream interface } }
By wrapping the original request with this class, you can access the cached input stream multiple times within the filter chain and beyond, allowing for both getParameterXXX and custom methods like doMyThing to read the parameters:
public class MyFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { MultiReadHttpServletRequest multiReadRequest = new MultiReadHttpServletRequest((HttpServletRequest) request); doMyThing(multiReadRequest.getInputStream()); chain.doFilter(multiReadRequest, response); } }
The above is the detailed content of How to Access HTTP Servlet Request Parameters Multiple Times Without Consumption?. For more information, please follow other related articles on the PHP Chinese website!