users@glassfish.java.net

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

From: Witold Szczerba <pljosh.mail_at_gmail.com>
Date: Sun, 30 May 2010 18:42:28 +0200

2010/5/30 Hassan Schroeder <hassan.schroeder_at_gmail.com>:
> On Sun, May 30, 2010 at 8:04 AM, Witold Szczerba <pljosh.mail_at_gmail.com> wrote:
>
>> OK, so how the "pass values to the view" part is supposed to be done?
>> Servlet has the "response" object and someone, sooner or later, will
>> have to write to it...
>
> But not your servlet. Your servlet(s) simply perform whatever logic
> they're intended to do and place the appropriate values into the
> request (or session) and then forward the request to the view. The
> container is responsible for writing that view to the response.
>
>> So, going back to my original question: how
>> should it look like? Should the "out.close();" happen unconditionally
>> (finally block)?
>
> It's irrelevant, you shouldn't be doing it, but theoretically, yes, of
> course; why would you *not* want that PrintWriter closed??
>
>> So, I was trying my luck with one level lower: servlets. Security +
>> full Java EE integration works like a charm here, it seems like a good
>> facade for AJAX calls. But, as I just said: sooner or later - it will
>> happen and data will go into PrintWriter.
>
> If you're doing it right, you'll never be calling a PrintWriter yourself. Not
> ever :-)
>

I am sorry, but still, I do not get it. You are saying my servlet is
supposed to place appropriate values into the request or session and
forward the request to the view. What does it mean the container is
responsible for writing view to the response?

Tell me if there is something wrong in such a case:
1) servlet is invoked with some parameter, for example: customer ID,
2) servlet takes customerId from request and asks some bean to fetch data,
3) said bean returns some object, let's say it is a Customer object,
4) servlets asks some marshaller, e.g. JAXB to write Customer object
to the output - passing its PrintWriter as a "sink".

According to what you say - it is wrong, as servlet should not write
data to the response, the container should do it. So in this case, my
servlet should place the "Customer" object into the request or session
(an then what?). What does it mean? Could you give me some tiny
example?