O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

9.2. Using an Expression Language

Problem

You need to parameterize text messages with variables and bean properties.

Solution

Use Commons JEXL to evaluate an expression containing references to bean properties. To reference properties of an object, create an expression using the bean property syntax introduced in Chapter 3. Surround each property reference with curly braces and a leading $, as in the following example:

${opera.name} was composed by ${opera.composer} in ${opera.year}.

Use the following code to “merge” an instance of the Opera bean with the above expression:

import org.apache.commons.jexl.Expression;
import org.apache.commons.jexl.ExpressionFactory;
import org.apache.commons.jexl.JexlContext;
import org.apache.commons.jexl.JexlHelper;

Opera opera = new Opera( );
opera.setName("The Magic Flute");
opera.setComposer("Mozart");
opera.setYear(1791);

String expr = 
    "${opera.name} was composed by ${opera.composer} in " +
    "${opera.year}.";

Expression e = ExpressionFactory.createExpression( expr );
               JexlContext jc = JexlHelper.createContext( );
               jc.getVars( ).put("opera", opera);
               String message = (String) e.evaluate(jc);

System.out.println( message );

This code puts an instance of the Opera bean in a JexlContext and evaluates the expression, producing the following output:

The Magic Flute was composed by Mozart in 1791.

Discussion

The previous example creates and populates an instance of the Opera bean: opera. An Expression object is then created by passing a String containing a JEXL ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required