java - 可以在循环中多次调用 ServletRequest.getInputStream() 吗?

标签 java servlets

在 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/

相关文章:

java - Java中如何生成固定长度的唯一标识符?

java - 全局 MySQL 连接还是每个请求一个连接?

java - Java Servlet 是否等同于 Web 服务

Java函数中的final变量

java - 首先在 Object.property1 上对 Map<String, Object> 进行排序,然后对于每个 Object.property1,按 Object.property2 排序

java - 为什么 Java 不能推断父类(super class)型?

java - Servlet 到 MYSQL 连接

java - 从输入区域返回空值

tomcat - 我可以在 servlet 映射中组合这些 url 模式吗?

java - 为什么 Byte.parseByte 的结果被识别为整数?