c:out

We can use the JSTL c:out tag to output an object. One could wonder which is the added value in using c:out instead of relying on EL. In few words, the answer is that c:out is way more flexible.

Let's think about this example: in our servlet we put an attribute on the request, currentTip, that represent a tip for web developers:
request.setAttribute("currentTip", "<b></b> tags make things bold!");
The problem is that the "bold" tag would be interpreted as a markup. And if we think about it, how could our page understand we don't want this to happen in this case?

So, if we naively write this in our JSP page:
This won't work as expected: ${requestScope.currentTip}
we won't see our "bold" tag opening and closing.

But if we use the c:out tag we'll see it. But before writing it in our JSP page we need to do some JSTL setup for our web application and our current page.

Done that, we can write:
<c:out value='${requestScope.currentTip}' />
This now work as expected, but now we could have the other problem: what if we actually want to print some bold text? In that case we don't want the "bold" tag to be managed as normal text. The way out is actually saying to c:out not to escape the XML text:
<c:out value="${requestScope.currentTip}" escapeXml="false" />
The escapeXml attribute is "true" by default. If we don't specify it, the XML characters in the printed string are converted to plain text. But when we don't want this feature, we have to explicitely turn it off.

The c:out standard tag behaves friendly with null values - it simply doesn't print anything. If we want to have some feedback, we could specify what we want it printed.

So, let's say we are about to print an hello message to the user. The user name should be specified in an attribute. If the attribute is null we could be call him "guest". We can write:
<b>Hello <c:out value="${user}" default="guest" />.</b>
<br /><b>Hello <c:out value="${user}">guest</c:out>.</b>

These two notations mean the same, choose the one you like most.

If the user attribute is actually defined, it will be used, otherwise we'll say hello to guest.

I wrote this post while reading the ninth chapter of Head First Servlet and JSP.

No comments:

Post a Comment