调用 request.getReader() 后重置 HttpRequest
有没有办法在 HttpRequest
上调用 getReader()
方法,然后“重置”请求,以便对 getReader()
的其他调用将不抛出java.lang.IllegalStateException
?
Is there a way to call the getReader()
method on a HttpRequest
and then "reset" the request so other calls to getReader()
will not throw java.lang.IllegalStateException
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就像其他人所说的那样,不,我认为没有办法重置请求。
我也遇到过同样的情况,希望在继续之前将请求的内容记录在 ServletFilter 中。这是论坛帖子,帮助我弄清楚如何创建一个像 Stephen C 所说的那样的 HttpServletRequestWrapper 。这将存储数据,以便您可以多次调用
getReader()
和getInputStream()
。Like other people have said, No I don't think there is a way to reset the request.
I have been in the same situation of wanting to log the content of the request in a ServletFilter before moving on. Here is a forum post that helped me figure out how to create a
HttpServletRequestWrapper
like Stephen C was talking about. That will store the data so you can callgetReader()
andgetInputStream()
multiple times.简单的答案是“否”。
该流不可重置,并且没有 API 方法允许您重新打开它。 (并且有充分的理由。它需要 servlet 基础设施保留输入的副本以防万一 servlet 决定重新打开流。这将是不必要的开销。)
如果您想要这样做这种事情,您将需要编写代码来保留自己的数据副本。如果您在 Filter(或 Tomcat Valve)中实现此功能,那么您可以创建一个 HttpServletRequestWrapper 来隐藏您已经读取数据的事实......正如 @Vineet 所建议的那样。
The simple answer is "No".
The stream is not resettable and there's no API method that will allow you to reopen it. (And for good reason. It would require the servlet infrastructure to keep a copy of the input just in case the servlet decided to reopen the stream. That would be an unwarranted overhead.)
If you want to do this kind of thing, you will need to write your code to keep its own copy of the data. If you are implementing this in a Filter (or a Tomcat Valve) then you could create a
HttpServletRequestWrapper
to hide the fact that you've already read the data .... as suggested by @Vineet.