Java Server Faces: Expression Language

The Expression Language (EL) specifies rules to write simple expressions for accessing and manipulating managed beans in an elegant manner. Specifically, EL expressions can set bean properties and can invoke arbitrary static and public methods.

An EL expression is written as #{…} or ${…}. The evaluation of EL expressions may happen at different times and is referred to as immediate evaluation and deferred evaluation. The former means that the expression is evaluated when the page is rendered and happens for expressions that take the form of ${…}. Expression in the form of #{…}, on the other hand, are evaluated at appropriate time during the page life-cycle and is referred to as deferred evaluation.

EL expression is also categorized as: value expressions and method expressions. Value expressions can either yield a value or set a value, whereas a method expression invokes a method.

Value expressions can be further categorized into rvalue expression and lvalue expressions. Expressions that can only read data, but cannot write it, are called rvalue expressions. Lvalue expressions can both read and write data. Expressions that evaluated immediately (i.e. in the form ${…}) are always rvalue expressions. Value expressions that use deferred evaluation syntax can act as both rvalue and lvalue expressions as well as method expressions.

Note that ultimately it is upto the framework how it treats #{…} or ${…} expressions. In Facelets, unfortunately, the ${…} is always treated exactly the same way as #{…}. So ${…} evaluation is also deferred in JSF. So, hereafter we shall only talk about expressions that take the form #{…}.

1. Value Expression

A value expression can be used in static text or in any tag attribute that can accept an expression. Value expressions (both rvalue and lvalue expressions) can refer to JavaBeans, collection objects, implicit object and enumerated types. For example, the following expression references a managed bean named myBean:


EL expression can contain implicit objects which are listed in Table 28.3:

To refer to properties of beans, implicit objects or items of a collection, we use the . or [] notation. For example, to refer to the message property, either of the following can be used:



We can use . or [] (or combination of them) in a cascaded fashion to refer to a nested property. For example, the following refers to the first property of the message property of myBean. #{myBean.message[‘first’]}

If the result of an EL value expression is an array or a List instance, elements of the array or the list can be obtained using [] notation with int indices. Here is an example:


However, to access Map elements, we use string literal as follows:


EL expressions can contain operators and literals which may be Boolean (true and false), Integer, Floating-point, String (single and back-slashed double quotes) and Null. Here are some examples:

It is also possible to write composite expression where more than one expression is written one after another as follows:


Each expression of the composite expression is converted to a String and then concatenated with any intervening text.

2. Method Expression

A method expression can be used to invoke arbitrary public methods of a bean, which return a value. A component tag uses method expressions to invoke methods that perform some processing for the component. For example, we can specify a method expression to the action attribute of

<h:commandButton> tag as follows:


<h:commandButton value=”Validate” action=”#{myBean.validate}”/>


Here, when the button is clicked, the method validate() on myBean is invoked. Like value expressions, we can also use . and the [] operators in method expressions. For example, the above code could have been written as:


<h:commandButton value=”Validate” action=,,#{myBean[,validate,]},,/>


The literal inside the [] is converted to String and is used to find the name of the method that matches it. The above method expressions merely call a method validate that does not take any parameters. However, we can also pass parameters to bean methods. Both the . and [] operators can be used for invoking method calls with parameters, as shown in the following expression syntax:



In the first expression syntax, expr1 evaluated to represent a bean object, and methodname is a string that represents a method in the bean object. In the second expression, expr2 is evaluated and cast to a string that represents a method in the bean represented by expr1. The parameters in parentheses are the arguments for the method invocation. Parameters can be zero or more values or expressions, separated by commas.

So the following expression invokes a method validate() with parameter ‘Me’.


3. Facelets

There are a set of special tags provided for page layout for web applications. These tags are called facelets tags. These tags must be qualified by the following namespace:


3.1. Templates

Often web pages have common parts such as header and footer. Templates allow us to place common part in a single file and refer to it from pages that need it. So, it allows content to be changed in one place, but used in multiple pages. When working with templates, we use the tags <ui:insert>, <ui:define>, <ui:include> and <ui:composition>.

A template is basically a page having some facelets tags that define the layout of the page. Here is an example (myTemplate.xhtml):

<html xmlns=””



<ui:insert name=”header” >

<ui:include src=”header.xhtml” />

</ui:insert> <br/>

<ui:insert name=”content” >

<ui:include src=”contents.xhtml” />

</ui:insert> <br/>

<ui:insert name=”footer” >

<ui:include src=”footer.xhtml” />




The <ui:insert> tag, as its name suggests, creates logical named segments. For example, the above template has three sections. The section contents are populated by the <ui:inciude> tag. So the above template is a composition of three documents header.xhtmi, contents.xhtmi and footer. xhtml, which are ordinary xhtml documents and usually contain <ui:composition> tag. This tag is used to group a number of elements which are used inside the template. To illustrate this, the relevant content of header.xhtml is given below:

<html xmlns:ui=””>







The content of the contents.xhtml and footer.xhtml will look similar. To use this template from another page (say index.html ), we can use <ui:composition> specifying URL of the template page to its template attribute as follows:

<ui:composition template=”myTemplate.xhtml” />

The content of the included template may be re-defined using <ui:define> tag as follows:

<ui:composition template=”myTemplate.xhtml”>

<ui:define name=”content”>

New Content



This replaces the content of content section by a new line of text. JSF also allows us to pass parameters to template file or an included file using <ui:param>. To hold the parameter in the header. xhtml, we write:




To pass a value to the header section, in myTemplate.xhtml, we write

<ui:insert name=”header” >

<ui:include src=”header.xhtml” >

<ui:param name=”header” value=”My Header” />



3.2. Custom Tags

Open source JSF implementation such as Oracle’s JSF offers just a few very standard, reusable UI components for forms, primitive tags for page layout and to display data. Fortunately JSF allows us to enhance their functionality of built-in tags or to create new custom tags. There are two ways to create custom tags: using <ui:composition> tag and using Java program.

Using Composition Tag

The following is a list of steps required to implement custom tags:

  • Create a source(xhtml) file and define tag contents using <ui:composition> tag.
  • Create a tag library descriptor (an XML file) and declare the above custom tag in it.
  • Register the tag library descriptor in web.xml.
  • Use the above declared tag in an XHTML file.

We shall develop a simple custom tag similar to <h:inputText> but has also a label. Here is the content of labeledInput.xhtml file.


<html xmlns=”” xmlns:h=””




<h:outputLabel value=”#{label}” />

<h:inputText size=”#{size}”/>




The result of the new tag is a composition of built-in <h:outputText> and <h:inputText> tags. The new tag will have only two attributes viz. label and size. This is stored in the directory jsf/ customTags/. Once the UI of the tag is defined, it is time to give it a name and specify its unique namespace and location of the source file. This is done on an XML file called tag library description. Here is sample tag library descriptor myTags.xml.

<?xml version=”1.0”?>









This defines a custom tag labeledInput in namespace The file is saved in web-inf/ folder of the web application. Inform the JSF runtime about this tag library in web.xml file as follows:







We can now use newly defined/declared tag in the test.xhtml file as follows:




<ct:labeledInput label=”First Name:” size=”10″/>

<ct:labeledInput label=”Middle Name:” size=”5″/>

<ct:labeledInput label=”Last Name:” size=”10″/>



At the top of the xhtml file, we first define the namespace for our tag. The final directory content is shown here. A sample output of this test.xhtml is also shown here:

Using Java Program

The previous method merely uses existing tags to compose a new one. To create an absolutely new one, we can write a Java class that defines the behaviour of the tag. All the classes representing the standard components extend javax.faces.component.uiComponentBase class that defines the default behaviour of a component class. Here is an example:

package tags;

import javax.faces.component.*;

import javax.faces.context.*;

@FacesComponent(value = ”tags.toUpper”)

public class ToUpper extends UIComponentBase {

public String getFamily() {

return ”toUpper”;


public void encodeBegin(FacesContext context) throws {

String value = (String) getAttributes().get(”value”);

if (value != null)




This class corresponds to a simple tag which will have a value attribute. The class translates the string in the value attribute to upper-case characters. The class is then registered in a tag library myTags.xml as follows:

Tag library: myTags.xml










Inform the JSF runtime about this tag library in web.xml file as before. We can now place this tag in the test.xhtml file as follows:




<ct:toUpper value=”Java Server Faces”/>



The final directory content is shown here:

3.3. Composite Components

JSF 2.0 addressed all the concerns to create a custom tag by introducing composite components which can be created using the following steps:

  • Create a folder resources/ under the web application root.
  • Create another folder under resource/ and create an xhtml file in this directory.
  • Define the content of the composite component in the xhtml file using <c:interface>, <c:attribute> and <c:implementation> tags.
  • Use the component from another xhtml file using namespace<folder-name> where folder- name is folder in resources directory containing the custom component.

Here is a file (labeledInput.xhtml) that defines a composite tag for a labelled input text.

<?xml version=”1.0″ encoding=”UTF-8″?>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”


<html xmlns=””




<c:attribute name=”label” />

<c:attribute name=”size” />



<h:outputLabel value=”#{cc.attrs.label}” />

<h:inputText size=”#{cc.attrs.size}” />



When defining composite component, the #{cc.attrs.attribute-name} expression is used to access the attributes defined for the composite component’s interface. So #{cc.attrs.iabei} and #{cc.attrs.size} expressions refer to the values of the attribute label and size attribute of composite component tag.

Now store the file labeiedinput.xhtmi in a folder named resources/test/, under the web application web directory. This directory resources / is considered to hold JSF components. To use this component, we can use the test.xhtml file as follows:




<ct:labeledInput label=”First Name:” size=”10″/>

<ct:labeledInput label=”Middle Name:” size=”5″/>

<ct:labeledInput label=”Last Name:” size=”10″/>



Note that the component library is accessed using the name space composite/test. In general, if the components are stored in a directory sample, they can be accessed using the namespace In our case the component itself is accessed through the <ct:labeledInput> tag.

3.4. Remove

Although, JSF engine does not process contents commented by <!— and —>, they do present in the rendered HTML page in the commented form and hence can be viewed by the clients. For example, the following JSF code

<!– <h:outputText value=”Hello World!” />–>

will appear at the client side as

<!– &lt;h:outputText value=”Hello World!” /&gt;–>

Moreover, JSF processes the value expression even commented by <!– and –> and outputs the result to the generated HTML page. For example, if #{myBean.message} returns a sting “Hi”, the following JSF code

<!–<h:outputText value=”#{myBean.message}” /&gt;–>

will appear at the client as

<!–&lt;h:outputText value=”Hi” /&gt;–>

This way some sensitive server-side code may get disclosed at the client side. JSF <ui:remove> may be used to prevent the JSF specific code to be rendered on client side. For example, the above JSF code may be hidden as:

<ui:remove><h:outputText value=”#{myBean.message}” /></ui:remove>

It does not output anything as desired.

4. Converter Tags

The value provided to a component is a string. Conversion from strings to Java objects and vice versa is necessary in many cases. For example, consider a text field where a user supplies his/her Date of Birth (DoB) in a pattern dd-MM-yyyy corresponding to a java.util.Date property of the backing bean.

The string must be converted properly to store the converted data in the property. Similarly, when the user response comes back, the text field must hold the Date value converted in dd-MM-yyyy pattern. Moreover, if the user doesn’t fill Dob field in the correct format, a message indicating the conversion failure should be displayed.

Oracle’s JSF provides many built-in convertor classes (Implementing the javax.faces.convert. Converter interface) to perform standard conversions between strings and simple data types in the package javax.faces.convert. Table 28.4: shows the list.

These classes are registered in JSF under a symbolic name shown in the middle column. Out of these 12 classes, last two classes DateTimeConverter and NumberConverter also have their own tags <f:convertDateTime> and <f:convertNumber> respectively. We can specify the format and type of the component data by configuring these tag attributes. Here is an example:


<html xmlns=”” xmlns:h=””




<h:inputText value=”#{}” >

<f:convertDateTime pattern=”dd-MM-yyyy” />


<h:commandButton value=”submit” /><br/>


<h:messages style=”color:red” />



The <f:convertDateTime> tag in the above code can convert a string in dd-MM-yyyy format to a Date type object and vice versa. Please note that the pattern is dd-MM-yyyy and not dd-mm-yyyy. The backing bean to hold the date is this:

package converter; import java.util.Date; import javax.faces.bean.*;



public class DateBean {

private Date date = new Date(); public Date getDate() {

return date;


public void setDate(Date date) { = date;



The date.xhtml produces the following output:

The converter classes (specifically which do not have tags) can also be used in the following ways:

  • Add the converter attribute to a component using name of the converter as the value.
  • Nest the f:converter tag within a component. Use this tag’s converterlD attribute to reference the converter’s name.

For example, the text box in the above could have been written as:

<h:inputText value=”#{}” converter=”javax.faces.DateTime” />

However, the default date format will be “dd MMM, yyyy”. Equivalently, The <f:converter> may be used as follows:

<h:inputtext value=”#{datebean.Date}” >

<f:converter converterid=”javax.Faces.Datetime” />


Other classes which do not have tags may be used using either of the above two ways. If JSF’s built-in converter classes do not fulfil our requirement, we can also write a custom converter of our own. Here are the basic steps to write a custom convertor:

  • Create a class implementing javax.faces.convert.Converter interface.
  • Implement getAsObject() and getAsString() methods of above interface.
  • Assign a unique id to the custom convertor using either @FacesConvertor annotation or faces-config.xml file.

Here is an example:

package converter;

import javax.faces.convert.*;

import javax.faces.context.FacesContext;

import javax.faces.component.UIComponent;

import javax.faces.application.FacesMessage;


public class URLConverter implements Converter {


public Object getAsObject(FacesContext fc, UIComponent c, String val) {

try {

return new;

}catch( e) {

FacesMessage msg = new FacesMessage(e.toString());


throw new ConverterException(msg);




public String getAsString(FacesContext fc, UlComponent c, Object val) {

return val.toString();



Here, the method getAsObject() converts the given string value into a URL object and getAsString() method converts the given object into a string representation. The @FacesConverter annotation registers this converter class with name “converter.URLConverter” for further reference. It could have been registered in the faces-cinfig.xmi file as follows:





We can then refer to this converter by its name using either converter attribute of a component as follows:

<h:inputText value=”#{converterBean.url}” converter=”converter.URLConverter” /> or using

<f:converter> tag as follows:

<f:converter converterId=”converter.URLConverter” />

The corresponding backing bean is shown below:

package converter; import javax.faces.bean.*; import;


@SessionScoped public class Bean {

private URL url;

public URL getUrl() { return url; }

public void setUrl(URL url) { this.url = url; }


A converter may also be registered by the @ManagedBean annotation. Consider the following is used for our URLConverter class:



public class URLConverter implements Converter {



This converter can be referred to as

<h:inputText value=”#{converterBean.url}” converter=”#{uRLConverter}” />

5. Displaying Messages

Oracle’s JSF implementation provides two tags <h:messages> and <h:message> to display messages in the client UI. The former is used to display all messages at once. By default, component-specific messages are shown. Set its globleOnly attribute to true to display only global messages as follows:

<h:messages globalOnly=”true” />

This tag can be placed anywhere in a JSF page. To display messages for a specific component, <h:message> tag is used. Its for attribute refers to the id attribute of the component whose messages are to be displayed:

<h:inputText id=”login” required=”true” />

<h:message for=”login”/>

A message may be a summary or a detailed description or both. The <h:message> and <h:messages> tags, by default, show the detail and summary message respectively. However, they can be controlled using the Boolean showSummary and showDetail attributes.

6. Validations

Often code that processes data expect clean, correct and useful data. So it is a good idea to validate data prior to forwarding them to processing code. Like other frameworks, JSF also provides facilities to validate data of editable components in the Process Validations phase of request processing life-cycle.

The most commonly used validation happens when a form field cannot be left empty (i.e. user must provide some information) and is implemented in JSF as an attribute required. All tags that implement EditabieVaiueHoider interface has this attribute. Here is an example:

<h:inputText required=”true” />

Oracle’s JSF provides some useful tags that can be leveraged to implement validation of any user input. These tags must be qualified by the namespace URI Here is an example:

<h:inputText value=”#{validateBean.temperature}”>

<f:validateLongRange minimum=”-273″ />


The above text box corresponds to the vaiidateBean’s temperature property that holds the temperature in Celsius. Since the lowest possible temperature is -273° C, it is restricted using minimum attribute of <f:validateLongRange> tag. A list of built-in validation tags with brief description is shown in Table 28.5:

This tells that the value of the text box must only contain 4 to 8 alphanumeric characters. Note that server-side data validation requires a client-server round trip. Data may be validated, if possible, at the client side using JavaScript code as follows:

<h:form id=”myForm”>

<h:inputText id=”txt” />

<h:commandButton value=”Click”

onclick=”var v = document.getElementById(‘myForm:txt’).value;

if(v.match(/^\w{4,8}$/)) return true;

else return false;” />


Note that JSF renderer may not retain the tag attributes values. For example, for the id attribute value “txt” will be substituted by the “myform:txt” which we have used in our getEiementByid() method. If the JSF implementation follows a different convention, or a different JSF implementation is used, the above code may not work properly.

Data validation may be done using a method of a backing bean. The declaration of the method will look like this:

public void <METHOD_NAME> (FacesContext context, UlComponent component, Object value) {    ..       }

JSF framework automatically calls this method at an appropriate time in the life-cycle. Here is a method added to our VaiidateBean class:

package validate;


public class VaiidateBean {


public void checkValue (FacesContext context, UlComponent component, Object value) throws ValidatorException {

if(Integer.parseInt((String)value) < -273) {

String summary = “temp can’t be less than -273”, detail= summary;

throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, detail ));




If the value is found to be less than -273, this exits by throwing a VaiidatorException() passing an instance of javax.faces.appiication.FacesMessage else the code exits normally. The message is queued in the messages list and displayed to the user. This method is now ready to be bound with a component using validator attribute:

<h:inputText validator=”#{validateBean.checkValue}” />

JSF also allows us to write a custom validator class that implements javax.faces.validator. Validator interface and provides the validate() method. Here is a sample example that validates temperature:

package validate; import javax.faces.component.*;

import javax.faces.context.*;

import javax.faces.validator.*;

import javax.faces.application.*;


public class TemperatureValidator implements Validator {


public void validate (FacesContext context, UIComponent component, Object value) throws ValidatorException {

if(Integer.parseInt((String)value) < -273) {

String summary = ”temp can’t be less than -273”, detail= summary;

throw new VaXidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, detail ));




The @FacesVaiidator annotation registers the class with the runtime as a validator. Since no value is specified for the @FacesVaiidator annotation, the name of validator will be the name of the class with the first letter in lower case i.e. temperatureVaiidator. The registration can be in the faces-config.xml file as follows:





This validator is then referred to in the vaiidatorid attribute of <f:vaiidator> tag:


<f:validator validatorTd=”temperatureValidator” />


Source: Uttam Kumar Roy (2015), Advanced Java programming, Oxford University Press.

Leave a Reply

Your email address will not be published. Required fields are marked *