users@glassfish.java.net

Re: servlet: try ... finally {out.close();} <-bad idea?

From: Hassan Schroeder <hassan.schroeder_at_gmail.com>
Date: Sun, 30 May 2010 06:57:53 -0700

On Sun, May 30, 2010 at 5:06 AM, Witold Szczerba <pljosh.mail_at_gmail.com> wrote:

> Hmmm... best practice is to never generate output from a servlet? What
> else servlet actually can do?

Process request input, interact with a database, do calculations, do
basically anything in the Model or Controller part of MVC, and pass
the appropriate values to the View.

> And what about the problem I mentioned, when after exception, the
> servlet container generated OK HTTP Status?

That's exactly the problem with directly writing output the way you're
describing: once you start, you've *already committed the response*
including the status (200 OK) header. If something blows up later in
your code there's no way to "unwind" it -- the response headers are
already on their way to the client. (You *could* buffer the response
and flush when done, but that isn't perfect either, for other reasons.)

OTOH, if you're using your servlet(s) to prepare the response values
to pass to a view object and something goes wrong, you can forward
to an appropriate error page, with an appropriate status header.

HTH,
-- 
Hassan Schroeder ------------------------ hassan.schroeder_at_gmail.com
twitter: @hassan