How to programmatically evaluate EL in a managed b

2019-05-14 04:56发布

问题:

I would like to add a simple template language to my application based on Seam / JSF to let the users compose their own email.

Since I don't want to create a new parser, I would like to use the Unified Expression Language setting the context all by myself.

How can I do that?

回答1:

If you're sitting inside the JSF context, then just use Application#evaluateExpressionGet() to programmatically evaluate a string containing EL expressions.

String unevaluatedString = convertMailTemplateToStringSomehow();
FacesContext context = FacesContext.getCurrentInstance();
String evaluatedString = context.getApplication().evaluateExpressionGet(context, unevaluatedString, String.class);
// ...

If you're not sitting inside the JSF context, then you'd need to use a standalone EL API, such as JUEL. Or, if you're already on EL 3.0 and the string represents the sole EL expression, then use the ELProcessor API.

ELProcessor el = new ELProcessor();
el.defineBean("bean", new Bean());
el.eval("bean.foo"); // Without starting #{ and ending } !
// ...