A JSF Expression Language Scratchpad

Being not very familiar with JSF and Expression Language I was looking for some kind of on-line try it out thing. I didn’t find one, so I made my own…

One simple backing bean:

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

@ManagedBean(name="bean")
public class EvaluationBean {
	
	String textA;
	String textB;
	String expression;
	String result;
	
	public String getTextA() {
		return textA;
	}

	public void setTextA(String textA) {
		this.textA = textA;
	}

	public String getTextB() {
		return textB;
	}

	public void setTextB(String textB) {
		this.textB = textB;
	}

	public String getExpression() {
		return expression;
	}

	public void setExpression(String evaluate) {
		this.expression = evaluate;
	}
	
	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}
	
	public void evaluate() {
		ELContext context = FacesContext.getCurrentInstance().getELContext();
		ExpressionFactory factory = ExpressionFactory.newInstance();
		ValueExpression valueExpression = factory.createValueExpression(
				context, expression, Object.class);
		try {
			Object value = valueExpression.getValue(context);
			if (value == null) {
				result = null;
			}
			else {
				result = value.toString();
			}
		}
		catch (Exception e) {
			result = e.getMessage();
		}
	}
}

and one Facelet:

<html lang="en"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">
    <body>
    
    	<h:form>
    		<p>Enter an EL expression in the expression field. Backing bean is 
    		named 'bean'. Fields can be accessed as \#{bean.textA} etc.</p>
    		
    		<table>
    		
    		<tr>
	    		<td><h:outputLabel>textA</h:outputLabel></td> 
	    		<td><h:inputText value="#{bean.textA}"/></td>
    		</tr>

    		<tr>
	    		<td><h:outputLabel>textB</h:outputLabel></td> 
	    		<td><h:inputText value="#{bean.textB}"/></td>
    		</tr>
    		
    		<tr>
				<td><h:outputLabel>expression</h:outputLabel></td> 
				<td><h:inputText size="50" value="#{bean.expression}"/></td>
    		</tr>
			
    		<tr>
				<td colspan="2"><h:commandButton type="submit" value="Evaluate" action="#{bean.evaluate}"/>
				</td>    	
    		</tr>
    		</table>
			
    	</h:form>
    
	    <h2>Result: #{bean.result}</h2>
    	
    </body>
</html>

And the resultant web page:

JSF EL Scratchpad

If you are also new to JSF and EL I hope you find it useful.

Comments are closed.