1

I am in reference to HttpServletResponse's sendError method:

void sendError(int sc,
               java.lang.String msg)
               throws java.io.IOException

... and the official documentation provided:

Sends an error response to the client using the specified status and clears the buffer. The server defaults to creating the response to look like an HTML-formatted server error page containing the specified message, setting the content type to "text/html". The server will preserve cookies and may clear or update any headers needed to serve the error page as a valid response. If an error-page declaration has been made for the web application corresponding to the status code passed in, it will be served back in preference to the suggested msg parameter and the msg parameter will be ignored.

If the response has already been committed, this method throws an IllegalStateException. After using this method, the response should be considered to be committed and should not be written to.

Can anyone please explain what is meant by "clears the buffer" and "If the response has already been committed"?

Community
  • 1
  • 1
balteo
  • 23,602
  • 63
  • 219
  • 412

1 Answers1

2

what is meant by "clears the buffer"

The code will response.resetBuffer() which basically resets any written and unflushed data of response body.


and "If the response has already been committed"?

If the response headers are already sent to the client. This is a point of no return. The server cannot take back already sent data from the client and re-send a different response.

An example of the normal flow is as below:

  1. user requests JSP
  2. JSP writes some HTML to response body
  3. some awkward code in midst of a JSP file throws an exception
  4. server calls response.sendError(500) so that HTML of HTTP 500 error page will be written
  5. user sees HTTP 500 error page

However, if between step 2 and 3 the response buffer is flushed (i.e. any so far written data gets actually sent from server to client), then the response is in a "committed" state. This cannot be resetted. The enduser basically ends up getting halfbaked HTML output representing the part until the point the exception has occurred.

That's also one of the reasons why doing business logic in a JSP file is a bad practice. See also a.o. How to avoid Java code in JSP files?

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555