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 10:08:37 -0700

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

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

Just like the container is responsible for writing static pages -- HTML,
CSS, JavaScript -- to the response.

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

Servlet:

Customer customer = Customer.find(customerId);
request.setAttribute("customer", customer);
RequestDispatcher rd =
this.getServletContext().getRequestDispatcher(someViewPage);
rd.forward(request, response);

JSP (someViewPage):

<p>Hello, ${customer.firstName}</p>

That's HTML, but you can as easily format as XML, JSON, whatever.
The container is responsible for interpreting it and writing the response.

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