如何从过滤器中查看消息?
我尝试使用 javax.servlet.Filter 来查看消息。
public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
BufferedReader reader = request.getReader();
if ( reader.markSupported() ) {
reader.mark( contentLen );
}
String content = reader.readLine();
// search some pattern
if ( reader.markSupported() ) {
reader.reset();
}
chain.doFilter( request, response );
}
最终收到请求的 servlet 会抛出此异常:
java.lang.IllegalStateException: getReader() has already been called for this request
根据 javadoc,这是正确的行为。
我的问题是如何读取输入流的内容?
我还尝试了 ServletInputStream is = request.getInputStream();
I tried to use a javax.servlet.Filter
to peek into a message.
public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
BufferedReader reader = request.getReader();
if ( reader.markSupported() ) {
reader.mark( contentLen );
}
String content = reader.readLine();
// search some pattern
if ( reader.markSupported() ) {
reader.reset();
}
chain.doFilter( request, response );
}
The servlet that finally receives the request throws this exeption:
java.lang.IllegalStateException: getReader() has already been called for this request
Which is correct behaviour according to the javadoc.
My questions is how can I read the content of the input-stream anyway?
I also tried ServletInputStream is = request.getInputStream();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
未经测试,但您可能可以
HttpServletRequestWrapper
覆盖getInputStream()
通过字节数组返回流,Not tested, but you could probably
HttpServletRequestWrapper
which overridesgetInputStream()
to return a stream over the byte array,遵循 @JB Nizet 的方法得到了以下代码:
Following the aproach from @JB Nizet led to this code:
ServletRequest.getInputStream() 和 ServletRequest.getReader() 是非此即彼的,因此如果其中一个已经被调用,另一个就会失败。您可以使用简单的 try-catch 来解决此问题:
注意!没有指定流或读取器应该可重置,因此如果您消耗了其中的任何字节,它们将不再可用到链中进一步的任何过滤器或 servlet。
ServletRequest.getInputStream() and ServletRequest.getReader() are either-or, so if either has already been called, the other one will fail. You can use a simple try-catch to navigate around this:
NOTE! It is not specified that the stream or reader should be resettable, so if you consume any bytes off it, they will not be anymore available to any filters or servlets further in the chain.