Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - HttpServlet: When is the response sent to the client?

I was little experimenting with some HttpServlet stuff to understand it better. I wanted to build the scenario that a request is incoming and I need to send the response accordingly and as fast as possible and to do later some more work within the servlet. From my current understanding, the response should only be send to the client when the doGet or doPost method was returned. But from my example, the response is already sent back to the client within the processing of the commands in the servlet. So it is already returned when I was not expecting it to be.

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            Logger.getLogger(DisplayHeader.class.getName()).log(Level.SEVERE, null, ex);
        }

        response.setContentType("text/plain; charset=ISO-8859-1");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        final StringWriter sw = new StringWriter();
        PrintWriter out = new PrintWriter(sw);
        //TODO most be implemented SynchronizedStatusCodeDimo
        out.println("StatusCode=0");
        out.println("StatusText=Accepted");
        out.println("paymentType=PaymentXY");
        out = response.getWriter();
        out.print(sw.toString());
        out.flush();
        out.close();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(DisplayHeader.class.getName()).log(Level.SEVERE, null, ex);
        } }

What is happening here, via Firebug I see that I already received the response generated after 510ms. I thought I would need more then 1500ms because of the sleeps. My understanding was based on this post here: Link

like image 560
fryk9 Avatar asked Apr 25 '26 01:04

fryk9


1 Answers

The HttpServletResponse will be controlled by your servlet container (Tomcat, Jetty etc.) .

If you write into the response the servlet container automatically flush the response after a defined buffer size (e.g Tomcat after 9000 byte). Usually you can configure it (in Tomcat with the parameter socketBuffer). This is the way it works, if you do not control it by yourself.

In your case, you control the response by your self and after you call response.flush() the response will be send to the client. If you had writte more the 9000 Byte (in Tomcat), the response will be send automatically (in the middle of it all).

(excuse my bad english)

like image 96
drkunibar Avatar answered Apr 27 '26 15:04

drkunibar