The last months, I often looked at web pages of projects using JSF and discovered an extensive use of the tag h:outputText
. It needs some practice to fast read HTML pages. But if the pages are cluttered with additional tags they become unreadable. When I asked the developer, why they designed the page like this, I often got the impression it was because they found it in the web or in some other part of the application, copied the code, and adapted it. This is a valid approach if the adaption phase contains improvement and consolidation. But, because of some uncertainty when to use the tag and when not to use it, the code was not cleaned up. Thus, I decided to write a short post, adding my 2 cents to the story.
Here is an example of an extensive use of outputText
:
<h:outputText value="#{user.firstName}"/> <h:outputText value="#{user.lastName}"/> ( <h:outputText value="#{user.role}"/>)
It is much more readable if the tag is omitted:
#{user.firstName} #{user.lastName} (#{user.role})
If this is more readable, why are so many developer (at least in my neighborhood) using the unreadable variant? From what I know about JSF, I would guess it is because of the support of JSP as renderer backend. When JSF was firstly introduced it only supported JSP. Because there were several architectural mismatches the usage of JSF was pretty painful. Then came Facelets. It allowed the developer to code his JSF page more or less with plain HTML. In JSF 2.0 Facelets was integrated into the JSF specification and I do not know any reasons to use JSPs in combination with JSF anymore.
The thing now is: With JSPs you need the outputText
tag, with Facelets you do not.
It is always good practice to prove the stuff you are telling. Thus, I wrote a tiny example application. You can find it here:
https://github.com/tnfink/JSFMyths.git
It demonstrates that the usage of outputText
has no effect. Even if you insert HTML-code into the text variable, it will be escaped independent of using the tag or not. Here is a snapshot of the application:
But of course, there are always exceptions to the rule. Here are some which I found important in real life applications:
- Conditional Output
- The attribute
rendered
can be applied to print a text only if a condition holds.<h:outputText value="#{details.description}" rendered="#{error}" />
- Formatting of dates and times
- The inner tag
convertDateTime
format a date or time value according to a specified format.<h:outputText value="#{user.birthday}"> <f:convertDateTime dateStyle="medium" timeZone="Etc/GMT" type="date" /> </h:outputText>
- Ajax
- To refresh a text via Ajax it needs an identifier. This can be provided by a
ouputText
tag.<h:outputText id="counterText" value="status.counter" /> <a4j:poll interval="500" reRender="counterText" />
I hope this post helps a little bit to reduce the number of unnecessarily used tags.