且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-04 14:20:04

回答我自己的问题:一旦方法执行完毕,doGet方法是否会将响应发送到客户端?

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

Yes, when the doGet (or any HttpServlet method, ex: doGet, doPost, etc.) method finishes executing it sends the response back to the client.

如果在这种情况下,如何保持连接打开以获得长轮询效果?

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

Using asynchronous Servlets (which I was using, however, I found my particular problem must be elsewhere, yet these answers are still relevant to the questions asked). On the ServletRequest object call the startAsync method, like so:

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

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

"This will notify the Web Container that at the end of the request call it should free the handling thread and leave the connection open so that other thread writes the response and end the connection."Reference Link.

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

Also, I will add the solution to my particular problem (the client wasn't receiving the response) was because in my Servlet, I wasn't calling the complete method on the AsyncContext object:

asyncContext.complete();