java - Servlet - 关闭连接但不关闭方法

标签 java servlets

我必须实现服务(servlet 2.5 或 3),该服务将在每个连接上发送 204 代码,但不会关闭线程。 我需要对收到的数据执行一些操作(例如打开新连接)。

可以关闭连接但不能结束方法吗?或者在连接关闭时启动另一个方法?

最佳答案

规范中尚不清楚,但它似乎可以在 Tomcat 7.0 中工作。

摘自 servlet 3.0 规范:

Closure of Response Object
When a response is closed, the container must immediately flush all remaining content in the response buffer to the client. The following events indicate that the servlet has satisfied the request and that the response object is to be closed:

  • The termination of the service method of the servlet.
  • The amount of content specified in the setContentLength method of the response has been greater than zero and has been written to the response.
  • The sendError method is called.
  • The sendRedirect method is called.
  • The complete method on AsyncContext is called.

根据我在 tomcat 7.0.32 上的测试,当 ContentLength 设置为 0 且输出流关闭时,Http 连接会在 servlet 的 service 方法结束之前关闭。

因此,根据您的要求,您可以在 servlet 中尝试以下操作:

response.setStatus(HttpServletResponse.SC_NO_CONTENT);
response.setContentLength(0);
response.getOutputStream().close();
// continue after connection with client is closed

但是注意我在规范中找不到任何确认信息,因此它无法与其他容器一起使用。

关于java - Servlet - 关闭连接但不关闭方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25400355/

相关文章:

java - 为什么我可以声明一个泛型数组但不能初始化它?

maven - 如何使用可嵌入的tomcat访问maven项目结构中的tomcat servlet

java - HttpAttributeListener 不起作用?

java - Servlet工作原理的疑问

java - 根据servlet中的输入参数更改编码

java - 在代码(Java)中或使用触发器(MySQL)在数据库中以编程方式更新数据?

具有不同格式的 Java Regex 数字提取

java - JSP 无法使用 ""修饰符找到 bean 类

java - 采用整数并返回所有可能的加法格式的算法

java - 在 JPA 命名查询中使用 postgres 函数 "lower"时出错