Ben Ripkens

back to blog index

Evaluate JSF expression in backing bean

When developing a JSF application you may find yourself in situations where it is easier to supply localized text from the backing bean then to use complex JSF expressions in a Facelet. This may also reduce code duplication when conditional behaviour can be reused.

The easiest way to retrieve localized text from one of the resource bundles is to use the javax.faces.application.Application#evaluateExpressionGet method. You can use it in the following way.

package nl.rug.search.odr.util;

import javax.faces.context.FacesContext;

/**
 *
 * @author Ben Ripkens <bripkens.dev@gmail.com>
 */
public class JsfUtil {

    public static <T> T evaluateExpressionGet(String expression, Class<? extends T> expected) {
        return JsfUtil.evaluateExpressionGet(FacesContext.getCurrentInstance(), expression, expected);
    }

    public static <T> T evaluateExpressionGet(FacesContext context, String expression, Class<? extends T> expected) {
        return context.getApplication().evaluateExpressionGet(context, expression, expected);
    }
}
package nl.rug.search.odr.util;

import nl.rug.search.odr.Filename;
import nl.rug.search.odr.SessionAttribute;

/**
 *
 * @author Ben Ripkens <bripkens.dev@gmail.com>
 */
public abstract class ErrorUtil {

    public static void showErrorMessageUsingExpression(String headline, String content) {
        headline = JsfUtil.evaluateExpressionGet(headline, String.class);
        content = JsfUtil.evaluateExpressionGet(content, String.class);

        showErrorMessage(headline, content);
    }

    public static void showErrorMessage(String headline, String content) {
        SessionUtil.addValues(
                new String[]{SessionAttribute.ERROR_TITLE, SessionAttribute.ERROR_CONTENT},
                new String[]{headline, content});

        JsfUtil.redirect(Filename.ERROR_WITH_LEADING_SLASH);
    }

    public static void showUknownError() {
        ErrorUtil.showErrorMessageUsingExpression("#{error['unknown.heading']}",
                "#{error['unknown.message']}");
    }

    // ...
}

These code samples are part of the Open Decision Repository project.

That's me, Ben.
Hey, I am Ben Ripkens (bripkens) and this is my blog. I live in Düsseldorf (Germany) and I am employed by the codecentric AG as a Software Engineer. Web application frontends are my main area of expertise, but you may also find some other interesting articles on this blog.