繁体   English   中英

doGet方法完成后,Servlet是否返回响应?

[英]Does Servlet return response after doGet method has finished?

显然, doGet方法的返回类型为void,因此,它不返回任何内容。 从这个意义上讲,我使用“返回”一词来表示将响应发送回请求它的客户端。

我正在尝试实现一个长轮询的Servlet。 最好在我有想要发回的东西之前不发送响应,这将是有益的。 因此,在doGet方法中,将连接的用户的ID和AsyncContext添加到映射中:

private ConcurrentMap<String, AsyncContext> contexts = new ConcurrentHashMap<>();
//...in the doGet method when I need to add the context...
contexts.put(userId, context);

然后,当我有东西要发回时,我可以检索适当的上下文并写入其响应输出流:

AsyncContext context = contexts.get(userId);
PrintWriter writer = context.getResponse().getWriter();
writer.write("something to send to the client");

但是,客户端似乎从未收到响应。 查看浏览器开发者控制台中的“网络”选项卡,可以看到GET请求已发送,然后返回(状态为200)。 这发生在我实际寄回东西之前。 这使我相信doGet方法完成后会返回响应。 也许正因为如此,在此之后,由于未打开连接,因此无法将任何内容发送到客户端。

一旦方法完成执行,doGet方法是否将响应发送给客户端? 在这种情况下,如何保持连接打开以产生长轮询效果?

要回答我自己的问题: Does the doGet method send the response to the client once the method is finished executing?

是的,当doGet(或任何HttpServlet方法,例如:doGet,doPost等)完成执行时,它将响应发送回客户端。

If this is the case, how can I keep the connection open for a long-polling effect?

使用异步Servlet(但是我发现我的特定问题一定在其他地方,但是这些答案仍然与所提出的问题有关)。 在ServletRequest对象上,调用startAsync方法,如下所示:

AsyncContext context = request.startAsync(request, response);

“这将通知Web容器,在请求调用结束时,它应释放处理线程并保持连接打开,以便其他线程写入响应并结束连接。” 参考链接。

另外,我将解决方案添加到我的特定问题(客户端未收到响应)的原因是,在我的Servlet中,我没有在AsyncContext对象上调用complete方法:

asyncContext.complete();

是的,当doGet()完成执行时,将刷新并关闭响应流。

长时间保持UI线程占用违反Java Enterprise最佳实践。

建议您宁愿在无响应的情况下立即返回,并在客户端(浏览器)端实现一个计时器,以使服务器如此频繁地轮询结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM