我正在尝试访问Java Servlet过滤器中的两个http请求参数,这里没有新内容,但是很惊讶地发现这些参数已经被消耗了!因此,它在过滤器链中不再可用。
似乎只有在参数进入POST请求正文(例如表单提交)时才会发生这种情况。
有没有办法读取参数而不消耗它们?
顺便说一句,解决此问题的另一种方法是不使用筛选器链,而是使用可以在已解析请求主体上运行的方面来构建自己的拦截器组件。由于您只需将请求InputStream转换为自己的模型对象一次,这样做也可能会更有效率。
InputStream
但是,我仍然认为要多次读取请求正文是合理的,尤其是在请求通过过滤器链移动时。通常,我会将过滤器链用于要保留在HTTP层的某些操作,这些操作与服务组件分离。
HTTP
正如Will Hartung所建议的那样,我是通过扩展HttpServletRequestWrapper,使用请求InputStream并实质上缓存字节来实现的。
Will Hartung
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(); } @Override public BufferedReader getReader() throws IOException{ return new BufferedReader(new InputStreamReader(getInputStream())); } private void cacheInputStream() throws IOException { /* Cache the inputstream in order to read it multiple times. For * convenience, I use apache.commons IOUtils */ cachedBytes = new ByteArrayOutputStream(); IOUtils.copy(super.getInputStream(), cachedBytes); } /* An inputstream which reads the cached request body */ public class CachedServletInputStream extends ServletInputStream { private ByteArrayInputStream input; public CachedServletInputStream() { /* create a new input stream from the cached request body */ input = new ByteArrayInputStream(cachedBytes.toByteArray()); } @Override public int read() throws IOException { return input.read(); } } }
现在,通过在过滤器链中传递原始请求之前,可以包装原始请求多次读取请求主体:
public class MyFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { /* wrap the request in order to read the inputstream multiple times */ MultiReadHttpServletRequest multiReadRequest = new MultiReadHttpServletRequest((HttpServletRequest) request); /* here I read the inputstream and do my thing with it; when I pass the * wrapped request through the filter chain, the rest of the filters, and * request handlers may read the cached inputstream */ doMyThing(multiReadRequest.getInputStream()); //OR anotherUsage(multiReadRequest.getReader()); chain.doFilter(multiReadRequest, response); } }
该解决方案还将允许您通过这些getParameterXXX方法多次读取请求正文,因为底层调用是getInputStream(),当然,它将读取缓存的请求InputStream。
getInputStream()
编辑
对于较新版本的ServletInputStream界面。您需要提供其他一些方法的实现,例如isReady,setReadListener等等。请参考下面的注释中提供的问题。
ServletInputStream
sReady
setReadListener