My blog has moved!

You should automatically be redirected in 6 seconds. If not, visit
and update your bookmarks.

Monday, 4 February 2008

Concatenating strings in JSF

To start the day off I though I'd share a quick tip using JSF. Say you have a list of messages:


ITEM_1=First item
ITEM_2=Second item
ITEM_3=Third item

Now, on your JSF page you would like to show one of these messages depending on the ID of the item to display. For example, you might have an list of beans containing items you'd like to display:


package quicktip;

public class Item {

/** Unique ID of the item. */
private int id;

/** Number of items. */
private int count;

public Item() {}

...usual getters and setters...


So, in your backing bean to the JSF page you have a method that constructs a DataModel containing items (I won't go into those details as it's not very exciting). For the sake of this example the signature of the method is public DataModel getItems();

Finally we get to the interesting bit, the actual JSF page.

... usual jsf stuff ...
<f:loadbundle basename="quicktip.Messages" var="msgs" />
<h:datatable value="#{backingBean.items}" var="item">
<c:set var="key" value="ITEM_#{}" />
<h:outputtext value="#{msgs[key]}" />
<h:outputtext value="#{item.count}" />

That's it. So, the real gist of the tip is that you can use the jstl tag to concatenating a string that you can re-use to fetch values from maps.

No comments: