简体   繁体   中英

java servlet PrintWriter#flush stop throwing Exception

I have the folowing servlet code:

@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();
    }
}

Log output is:

MyServlet::doGet 1
MyServlet::doGet 2

Browser output is:

Some text 1
Some text 2

But in browser output I expected the NullPointerException.

When I comment flash() call

//writer.flush();

the NullPointerException occurs.

I know that the flush() call immediately flush content to response and also commit response. But I do not get why this is blocking the exception throw, because at the same time "Some text 2" and "MyServlet::doGet 2" texts came to output.

Will be glad for any ideas. Thanks.

But I do not get why this is blocking the exception throw

It doesn't "block" the exception. The exception still happens.

However, the servlet container handles exceptions by doing a requestDispatcher.forward() call to an error page or a httpServletResponse.sendError() call, and that cannot be done if the response has already been committed.

Since the response was been committed, the client simply cannot be notified about the error. The error is still logged though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM