Don't Close Servlet OutputStream or PrintWriter

I don't think web app developers need to close ServletOutputStream or PrintWriter in servlet classes. They are created and managed by the web container, and web components should not interfere with its lifecycle. If you do close them inside your servlet service/doGet/doPost methods, it won't cause trouble for a fault-tolerant container.

When NetBeans generates a new servlet, it does close the PrintWriter in processRequest method:

protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
/* TODO output your page here
out.println("<title>Servlet MyServlet</title>");
out.println("<h1>Servlet MyServlet at "
+ request.getContextPath () + "</h1>");
If NetBeans insists on closing ServletOutputStream, the safe way is to close it in a finally block.

In short, don't close servlet OutputStream or PrintWriter, just as you won't close System.out.


Anonymous said...

First, let me say I enjoy your blog and the obvious amount of time you put into the content you post.

You say don't do the close in a servlet and your reason is that the container handles the close for the developer. If that is the case why does NetBeans put that code in each servlet? Should I modify the template that Netbeans uses adding a finally block or just remove the close?


howto said...

Thanks for the comments. I'm glad you like it.

I would just remove that line.

To modify templates in NetBeans 5.x, go to tools | Template Manager, select the template and edit it.

In 4.x, go to Tools | Options, then Source Creation and Management on the left panel, expand Templates node, right-click the one you want to edit, and choose edit from the context menu.

אמיר said...

found a good reason to not close the writer - sometimes you want to wrap the servlet response with some text. the straightforward way to do it is to write a JSP and use tag that transfers the request and response to the servlet. however, if the servlet closes the response writer, the calling JSP can't write to the response after including the servlet.

Anna said...

Great and Useful Article.

Online Java Training

Java Online Training India

Java Online Course

Java EE course

Java EE training

Best Recommended books for Spring framework

Java Interview Questions

Java Course in Chennai

Java Online Training India

Membuat Pupuk Organik dari Kotoran Sapi said...

great! thanks for sharing

June said...

This post is exciting.

eMexoT said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

Internet Of Things training in electronic city