Saturday, January 21, 2012

How-to: Accessing EL expressions from java code

If you need evaluate EL expression directly from backin bean code, you can do it in three steps:
 
//get current EL context
javax.el.ELContext elContext = FacesContext.getCurrentInstance().getELContext();
 
//get the expression factory (for JSF or ADF).
javax.el.ExpressionFactory expressionFactory = 
FacesContext.getCurrentInstance().getApplication().getExpressionFactory();
 
//Create value expression as the EL I'm evaluating is a value e.g. #{bean.property}. 
//Create MethodExpression if the EL is a method e.g. #{bean.method()}
javax.el.ValueExpression valueExpression = 
expressionFactory.createValueExpression(elContext, "#{your.expression}, 
WhateverYouAreExpecting.class);
 
// get value and dont' forget to cast.
 
But if you're a little lazy, you can use JSFUtil class, which provides various utility methods that are handy to have around when working with JSF EL. The class is available to download from https://sourceforge.net/projects/wshfaces (likaonJsfUtils.jar).

The class provides methods such as:
  • public static Object getValueEl(String el) (Usage example: JSFUtil.getValueEl("#{bean.property}")
  • Programmatic invocation of a method that an EL evaluates to: public static Object invokeEL(String el)
  •  Method which sets a value into an EL object: public static void setValueEl(String el, Object val)
  •  Function which returns managed bean object: public static Object getManagedBean(String beanName), usage example: JSFUtil.getManagedBean("#{SessionBean1}")
  • and so on:)

No comments:

Post a Comment