官方文档解释的 HttpServletResponse 的 sendError 方法的方面

Aspects from HttpServletResponse's sendError method explained by the official documentation

我参考了HttpServletResponsesendError方法:

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

...以及官方提供的文档:

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.

谁能解释一下“清除缓冲区”和“是什么意思如果响应已经提交"?

what is meant by "clears the buffer"

代码将 response.resetBuffer() 基本上重置任何已写入和未刷新的响应数据 body。


and "If the response has already been committed"?

如果响应 headers 已经发送到客户端。这是一个没有的点return。服务器无法从客户端取回已发送的数据和 re-send 不同的响应。

正常流程示例如下:

  1. 用户请求JSP
  2. JSP 写一些 HTML 到响应 body
  3. JSP 文件中的某些笨拙代码引发异常
  4. 服务器调用 response.sendError(500) 以便写入 HTML 的 HTTP 500 错误页面
  5. 用户看到 HTTP 500 错误页面

但是,如果在第 2 步和第 3 步之间刷新响应缓冲区(即,到目前为止写入的任何数据实际上都从服务器发送到客户端),则响应处于 "committed" 状态。这无法重置。最终用户基本上最终得到代表部件的半成品 HTML 输出,直到发生异常为止。

这也是为什么在 JSP 文件中执行业务逻辑是一种不好的做法的原因之一。另见 a.o。 How to avoid Java code in JSP files?