Does Servlet return response after doGet method has finished?

前端 未结 2 723
暖寄归人
暖寄归人 2021-01-20 02:16

Obviously, the doGet method has a return type of void, so, it doesn\'t return anything. In this sense, I\'m using the word \"return\" to mean send the response

相关标签:
2条回答
  • 2021-01-20 02:28

    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.

    0 讨论(0)
  • 2021-01-20 02:36

    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();
    
    0 讨论(0)
提交回复
热议问题