在 servlet 中遇到一些执行此操作的代码:
while ((read = request.getInputStream().read(bytes)) != -1)
buffer.write(bytes, 0, read);
虽然在大多数情况下,request.getInputStream()
只是在某个地方返回一个字段,但我认为可能存在动态包装器或类似的东西,可能会进入不良状态。
文档中是否有关于执行此类操作的内容,我可以将其用作将 getInputStream()
代码拉出循环的案例?
最佳答案
多次调用getInputStream()
是可以的,Servlet规范只是禁止它与getReader()
一起使用。根据the ServletRequest#getInputStream()
method javadoc :
Retrieves the body of the request as binary data using a ServletInputStream. Either this method or getReader() may be called to read the body, not both.
Returns:
a ServletInputStream object containing the body of the request
Throws:
- IllegalStateException - if the getReader() method has already been called for this request
- IOException - if an input or output exception occurred
特定的 Servlet 实现可以自由地返回包装器对象,但最终人们应该总是期望 ServletInputStream
可以在某个时刻抛出 IOException
(例如连接重置)。
以Apache Tomcat为例,HTTP连接处理逻辑在 AbstractProtocol.ConnectionHandler.process()
method并且防御力很强。 HTTP连接和底层套接字的清理代码runs after catch(Throwable )
因此应用程序错误不应干扰资源清理。
关于java - 可以在循环中多次调用 ServletRequest.getInputStream() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53602262/