我有以下 servlet 代码:
@WebServlet("/my")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("MyServlet::doGet 1");
PrintWriter writer = resp.getWriter();
writer.write("Some text 1 \n");
writer.flush();
writer.write("Some text 1 \n");
System.out.println("MyServlet::doGet 2");
throw new NullPointerException();
}
}
日志输出为:
MyServlet::doGet 1
MyServlet::doGet 2
浏览器输出是:
Some text 1
Some text 2
但在浏览器输出中我期望出现 NullPointerException。
当我评论 flash() 调用时
//writer.flush();
发生 NullPointerException。
我知道flush()调用会立即刷新内容以响应并提交响应。但我不明白为什么这会阻止异常抛出,因为同时输出“Some text 2”和“MyServlet::doGet 2”文本。
很高兴有任何想法。 谢谢。
最佳答案
But I do not get why this is blocking the exception throw
它不会“阻止”异常。异常仍然发生。
但是,Servlet 容器通过对错误页面执行 requestDispatcher.forward()
调用或 httpServletResponse.sendError()
调用来处理异常,而这不能被如果响应已经提交,则完成。
由于响应已提交,因此客户端根本无法收到有关错误的通知。但错误仍然被记录。
关于java servlet PrintWriter#flush 停止抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55401572/