Pulling a value off of a component – sounds easy enough? Well, it is, but there’s a little gotcha that BalusC was kind enough to explain for me.
The UIComponent provides a .getAttributes() that returns, as expected, a map containing the keys and the attribute values. For a static attribute, this works just fine.
1 2 3 4 5 |
private void checkComponent(UIComponent component) { if (component.getAttributes().containsKey("ourAttribute")) { System.out.println("Found the attribute, value is " + component.getAttributes().get("ourAttribute")); } } |
In slightly more complicated cases, where we want to extract values that are derived from an EL expression, this does not work, as explained to me by BalusC in the afore-linked question. Basically, the EL expression is not evaluated until the get is called, so the key does not exist, so containsKey returns null.
Instead, we can just try to get the value and do a null check. This works for both static and non-static attributes, so seems to be the way to go.
1 2 3 4 5 6 |
private void checkComponent(UIComponent component) { Object attributeValue = component.getAttributes().get("ourAttribute"); if (attributeValue != null) { System.out.println("Found the attribute, value is " + attributeValue); } } |
Note that in the case where the attribute was dynamic and the EL evaluates to null, this will not pick up the attribute at all. We can expand this slightly to check for that, by checking if there was a value expression set for the attribute.
1 2 3 4 5 6 |
private void checkComponent(UIComponent component) { Object attributeValue = component.getAttributes().get("ourAttribute"); if (attributeValue != null || component.getValueExpression("ourAttribute") != null) { System.out.println("Found the attribute, value is " + attributeValue); } } |
Many thanks for your article. It is exactly what I was looking for.