1

I have to implements service (servlet 2.5 or 3) that will send 204 code on every connection but not close the thread. I need do some stuff with the data I received (like open new connection).

It is possible to close connection but not end method? Or start another method when connection is closing?

Mateusz
  • 690
  • 1
  • 6
  • 21

2 Answers2

1

Well it is unclear in the specs, but it seems to work in Tomcat 7.0.

Extract from the specs for servlet 3.0 :

Closure of Response Object
When a response is closed, the container must immediately flush all remaining content in the response buffer to the client. The following events indicate that the servlet has satisfied the request and that the response object is to be closed:

  • The termination of the service method of the servlet.
  • The amount of content specified in the setContentLength method of the response has been greater than zero and has been written to the response.
  • The sendError method is called.
  • The sendRedirect method is called.
  • The complete method on AsyncContext is called.

From my tests on a tomcat 7.0.32, the Http connection is closed before the end of the service method of the servlet when ContentLength is set to 0 and the output stream is closed.

So per you requirements, you could try the following in your servlet :

response.setStatus(HttpServletResponse.SC_NO_CONTENT);
response.setContentLength(0);
response.getOutputStream().close();
// continue after connection with client is closed

But BEWARE I could find no confirmation in the specs so it could not work with another container.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException {
        //Send 204 back
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        // Continue with you logic here
        .
        .
        .
        .
Nikola Dimitrovski
  • 720
  • 1
  • 10
  • 23