7/15/2006

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 {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
/* TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet MyServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet MyServlet at "
+ request.getContextPath () + "</h1>");
out.println("</body>");
out.println("</html>");
*/
out.close();
}
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.

4 comments:

Erik Weibust 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?

Erik

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