Does Servlet return response after doGet method has finished?

狂风中的少年 提交于 2019-12-02 00:57:55

To answer my own questions: Does the doGet method send the response to the client once the method is finished executing?

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

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

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);

"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.

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();

Yes, the response stream is flushed and closed when doGet() finishes executing.

Keeping UI threads occupied for extended periods of time violates Java Enterprise best practice.

Recommend you rather return immediately if nothing to respond, and implement a timer on the client (browser) side to poll the server for results every so often.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!