Friday, October 19, 2012

JSF 2.x Tip of the Day: Programmatically Creating EL ValueExpression

A common need is to create a ValueExpression for use in binding a JSF component attribute to a value in the JSF/CDI managed beans.

This is a convenience method that I have created to create these expressions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
 * Creates a {@link ValueExpression} that wraps an object instance. This
 * method can be used to pass any object as a {@link ValueExpression}. The
 * wrapper {@link ValueExpression} is read only, and returns the wrapped
 * object via its {@code getValue()} method, optionally coerced.
 *
 * @param expression The expression to be parsed.
 * @param expectedType The type the result of the expression will be coerced
 * to after evaluation.
 * @return The parsed expression.
 */
public static ValueExpression createValueExpression(String expression, Class<?> expectedType) {
    FacesContext context = FacesContext.getCurrentInstance();
    return context.getApplication().getExpressionFactory()
            .createValueExpression(context.getELContext(), expression, expectedType);
}
Here is an example of how to use it.
1
2
UICommandLink clink = (UICommandLink) application.createComponent(UICommandLink.COMPONENT_TYPE);
clink.setValueExpression("value", createValueExpression("#{indexBean.columnHeader}", String.class));
In this example I bind the <h:commandLink/> value programmatically to the @ManagedBean called IndexBean value called columnHeader.

0 comments :

Popular Posts