Accessing Map Entries With Dot Notation

This may be something that is old news to everyone else in facelets, but I just found out that you can access map entries using dot notation in facelets code.  Where is this handy?

Let’s say you have a facelets component that you wrote to display certain properties of a complex java object.  The component looks something like this.

    <!-- various styling, action, etc. -->

    <h:outputText value="#{entity.myValue}" />
    <h:outputText value="#{entity.yourValue}" />

    <!-- various styling, actions, etc. -->

You now decide that you like the formatting and actions in this component and want to use it with something else.  You don’t want to add myValue and yourValue to your other entity, nor do you want to create a facade or container class that just contains those properties that you are using in the facelets component.

One solution would be to create a map that contains the values you need for the component.  This doesn’t require a new concrete Java object and allows you to re-use the facelets component.

So, in the facelets page or component that includes your custom component you could do the following

<z:myComponent entity="#{myBean.propertyMap}" />

And in your controller bean or whatever, you could have a simple method

public Map<String, String> getPropertyMap()
    // get your entity
    Map<String, String> map = new HashMap<String, String>();
    map.put( "myValue", myEntity.getSomethingForMyValue() );
    map.put( "yourValue", myEntity.getSomethingForYourValue() );
    return map;

Now, the awesome magic is that the facelets component above will be able to reference the map values by name using dot notation in the component.  It doesn’t care if the “entity” you pass in is a simple map, or a Java object with proper getters and setters for the properties.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s