无消耗访问HTTP Servlet请求参数
问题:
访问多个HTTP请求时Servlet 过滤器中的参数,初始参数访问会消耗这些参数,使其无法用于后续使用。这个问题在参数驻留在请求正文中的 POST 请求中尤其容易出现。
解决方案:
要访问参数而不消耗它们,您可以扩展 HttpServletRequestWrapper 并实现自定义方法缓存输入流:
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 } }
通过使用此类包装原始请求,您可以访问在过滤器链内外多次缓存输入流,允许 getParameterXXX 和 doMyThing 等自定义方法读取参数:
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); } }
以上是如何无消耗地多次访问HTTP Servlet请求参数?的详细内容。更多信息请关注PHP中文网其他相关文章!