In this article will look at JSP Expression Language. We will cover the creation of a JSP Page using the Unified Expression Language including the use of implicit variables. This is the second article of four on JavaServer Pages. In the first article, “Tutorial:Review of JavaServer Pages JSP for the Web Component Developer Exam” we provide a review of JavaServer Pages and the functionality available to the developer to create dynamic content and template text. This is part of a series of articles to help you prepare for the web component developer exam.

Using the JSP Expression Language

The Expression Language (EL) is derived from the work that was done in the creation of both JavaScript as well as XPath. EL was introduced along with Java Standard Tag Library 1.0. EL facilitated the setting of action attributes based on runtime data through various sources. It was later incorporated as part of the JSP 2.0 specification to be used in generally for action attributes as well as tag libraries. In version 2.1, the Expression Language for JSP was merged with the expression language for JavaServer Faces into what is called the unified expression language. One of the key reasons for this was to enable the mixing of JSP content with JavaServer Faces tags without any conflicts caused by differences in the lifecycles of JSP and JSF. Using the unified expression language, web designers can do the following tasks:
  • Read dynamically application data stored in JavaBean components, implicit objects and other data structures
  • Write dynamically data to forms, JavaBean components
  • Invoke arbitrary public and static methods
  • Perform dynamically arithmetic operations

As well for custom tag developers, you can specify the type of expression that a custom tag will accept. We we look at these expressions below.

Types of Evaluation Expressions

There are two types of expression evaluations that can occur. This is either an expression is evaluated either immediately by the JSP engine or evaluated later by the underlying technology using the expression language. With immediate evaluation the JSP engine immediately evaluates the expression and then returns the result when the page is first rendered. In deferred evaluation the technology using the expression language will employ its own means to evaluate the expression at a later point in the page’s life cycle when it considers it is appropriate to do so. Expressions for immediate evaluation use the ${} syntax, while expression for deferred evaluation use the #{} syntax that was introduced for JavaServer Faces technology. JavaServer Faces uses a multiphase life cycle which is the reason behind the use of deferred evaluation expressions. During the JSF life cycle, component events are handled, data is validated, and other tasks are performed all in a particular order. Therefore evaluation of expressions are deferred until an appropriate point in the life cycle.

Immediate evaluation
Immediate expressions can only be used within template text or as the value of a JSP tag attribute that can accept runtime expressions. An example is shown below where a tag whose value attribute references an immediate evaluation expression that returns the total number of items for a session-scoped bean named count:

XML Code: Example of Immediate Evaluation Expression
<fmt:formatNumber type="number" maxFractionDigits="3" groupingUse="false"
The JSP engine evaluates the expression, ${sessionScope.count}, converts it, and passes the returned value to the tag handler. If you’re using immediate evaluation expressions they can only be read-only value expressions. For example, you could use the above expression to set the total count.

Deferred Evaluation
Deferred evaluation expressions can be evaluated at other phases of a page life cycle as defined by whatever technology is using the expression. With JavaServer Faces the controller can evaluate the expression at different phases of the JSF life cycle depending on how the expression is being used in the page. Below we give an example of using a JavaServer Faces inputText tag. This tag is for rendering a text field component that is used for user input. In the example, the inputText tag’s value attribute references a deferred evaluation expression that points to the firstName property of the customer bean.

XML Code: Example of an Deferred Evaluation Expression
<h:inputText id="firstName" value="#{customer.firstName}" />
During the initial request of the page with this tag, the #{customer.firstName} expression is evaluated during the render response phase of the life cycle. In this phase, the expression accesses the value of firstName from the customer bean similar to what was done with immediate evaluation.

During a postback, JavaServer Faces will evaluate the expression when the value is retrieved from the request, validated, and is propagated to the customer bean.
As explained previously the deferred evaluation expressions can be value expressions that can be used to read and write data as well as method expressions.

Results of an Expression Evaluation
There are two type of expression evaluation. There is value expression which references data and method expression which invokes a method. Within a value expression, you have rvalue expression are only for reading a value, and an lvalue expression can be used for reading and writing a value to an external object.

Expressions that are immediately evaluated can only be rvalue expressions and use the ${} delimiters. Expression that can be deferred can be either rvalue or lvalue expressions. They use the #{} delimiters. For example, in the following two expressions:

XML Code: Example of Expression
<taglib:tag value="${customer.firstName}" />
<taglib:tag value="#{customer.firstName}" />
The first one uses immediate evaluation syntax and the latter uses deferred evaluation syntax. The first expression accesses the firstName property, gets its value, and the value is added to the response and is then rendered on the page. The similar sequence of events takes place with the second expression but in this case, the tag handler can defer the evaluation of the expression to a later point in the JSF page life cycle. In JSF, the second tag’s expression is evaluated immediately during an initial request for the page. This expression acts as an rvalue expression. During the postback, the expression can be used to set the value of the firstName property with user input. In this context, it will act as an lvalue expression.

Objects You Can Reference Using Value Expressions
A user can reference the following type of object’s properties or attributes for rvalue and lvalue expressions:
  • JavaBeans components
  • Collections
  • Java SE enumerated types
  • Implicit objects

To reference these objects, just write an expression using the variable name with which you created the object. For example, the following expression references a JavaBeans component called cargo.

XML Code: Example of Expression Referencing an Object
When the web container identifies a variable in an expression, it will evaluate it by looking up its value based on the behavior of PageContext.findAttribute(String), where the String argument is the name of the variable. So in the case of the expression ${cargo}, the container will look for the variable cargo in the page, request, session, and application scopes and will return its value. If no customer variable is not found, a null is returned. For implicit objects, a variable that matches one of the implicit objects will return that implicit object instead of the variable’s value.

If you were to use a custom EL resolver, you could can the resolving of variables to suit your needs. This is a new feature of unified EL. For example, your resolver could intercept objects with the name cargo and return the value of the expression ${cargo} via the EL resolver. You cannot use this to override implicit objects.

Referring to Object Properties Using Value Expressions
If you want to reference a bean’s properties, a collections’ items, an Enum instance or an implicit object’s attributes, you use notation that is similar to ECMAScript (i.e. . or [] notation) For example to reference the id property for a cargo bean, you can use one of these expressions:

XML Code: Example of a Simple Expression
In the second expression, inside the square brackets is a String literal that is the name of the property to reference. You have the choice of using double or single quotes for the String literal. It is possible to combine both the . and [] notations as in the following:

XML Code: Example of an Expression Using . and [
You can use this for referencing enum properties but you need to follow JavaBean component conventions. So you must have at least defined an accessor method for the property (i.e. getXXX) so that the expression can reference it. An example of this is shown below for an Enum class for shapes that has a method for getting the area of the shape:

XML Code: Example of an Expression Using Enum
For accessing an item in an array or list, you need to use either the [] notation with an int value or a literal value that can be coerced to int. Some examples of this are shown below:

XML Code: Example of an Expression Using [
In contrast, an item in a Map can be accessed using a string literal key; no coercion is required:

XML Code: Example of Expression Using a Map
You can also use rvalue expression to refer directly to values from arithmetic operations or literal values. Examples are shown below:

XML Code: Example of RValue Expression
${cargo.weight * 1.2}
The following literals are defined as part of the unified expression language:
  • Boolean- true and false
  • Integer - similar to Java
  • Floating point - similar Java
  • String - can be with either single and double quotes.
  • Null: null

The Use of Value Expressions
You can use Value expressions with the ${} delimiters in the following places:
  • In static text
  • In a standard or custom tag attribute that accepts an expression

The static text value of an expression is computed and then inserted into the current output. Below is an example of an expression embedded in static text:

XML Code: Example of Embedded Expression in Static Text
    foo text ${expr} morefoo text
If you have static text in the tag body and the body is declared to be tag dependant, the expression will not be evaluated. You can only use lvalue expressions only in tag attributes that accept lvalue expressions. The means of setting a tag attribute using either rvalue or lvalue expressions are the following:
Using a single expression construct where the expression is evaluate and the result is converted to the attribute’s expected type:
XML Code: Example of Single Expression
<foo:tag value="${expr}"/>

<moo:tag value="#{expr}"/>

With composite expressions where one or more expressions are separated or surrounded by text. These kids of expressions are evaluated left to right where the expression is converted to a String and then concatenated with the surrounding text. The result is the converted to the attribute’s expected type:
XML Code: Example of Composite Expression
<foo:tag value="hohum${expr}${expr}text${expr}"/>

<moo:tag value="fofum#{expr}#{expr}text#{expr}"/>

With text that is known as a literal expression. Here, the attribute’s String value is converted to the attribute’s expected type. These are used for any tag attributes that are of type enum. These type of value expressions have special syntax rules. See your documentation for more information on literal expressions:
XML Code: Syntax of Value Expression
<some:tag value="feefiifoofum"/>

Any expression used for setting attribute values is evaluated within the context of the expected type. If the result of the expression evaluation doesn’t match the expected type exactly then a type conversion is done. So if you have an expression like the following:

XML Code: Example of Value Expression
where this is the value of an attribute of type float, the result will lead to the following conversion:

XML Code: Example of Value Expression
Looking at Method Expressions
Unified expression language also supports deferred method expressions. Method expressions are used to invoke an arbitrary public method, which can have a result. This is similar in unified EL to the use of functions. There are numerous differences between method expressions and functions. We will talk about functions more in depth a bit later.

Method expressions are used primarily with JavaServer Faces, but have been made available to a wider audience through the unified expression language. To better understand the use of method expressions we will look at how it is used in JavaServer Faces. In JavaServer Faces, a UI component on a page is represented by a component tag. Method expressions are used by the component tag to invoke methods to perform some processing for the component. These methods are used for handling events generated by the components as well as validating component data. An example of this is shown below:

XML Code: Example of Method Expression
        action="#{cargo.submit}" />
Here we have a UIInput text field component that is represented by the inputText tag. This has a validator attribute of the inputText tag that references a method, called validateId, in the bean, called cargo. The Tag Library Descriptors (TLD) that defines the inputText tag specify what signature the method referred to in the validator attribute should have. This is the same for the cargo.submit method referenced by the action attribute of the commandButton tag. The TLD for the commandButton tag specifies that any submit method must return an Object instance specifying the next page to which to navigate after the button of the commandButton tag is pressed.

The submit method is invoked during the invoke application phase of the life cycle and the validation method is invoked during the process validation phase of the life cycle. Note that since a method are invoked during different phases of the life cycle, method expressions must always use the deferred evaluation syntax.

As with lvalue expressions, method expressions can use the . and [] operators as was shown earlier in the article. So an expression like the following:

XML Code: Example of LValue Method Expression
is the equivalent of this:

XML Code: Example of Equivalent LValue Method Expression
As the literal inside the [] is converted to a String and is used to search the name of the method that matches it. Once a match is found, the method is invoked or information about the method is returned.

You can only use method expressions in tag attributes in the following ways:
  • With a single expression construct, where bean refers to a JavaBeans component and method refers to a method of the JavaBeans component.
  • With text only to support literals with action attributes primarily in JavaServer Faces.
  • When the method referenced in the expression is invoked, the String literal that is returned is converted to the expected return type based on the tag’s TLD.

Examples of both are shown below:

With a single expression construct:
XML Code: Example of Method Expression With Single Expression Construct
<foo:tag value="#{bean.method}"/>
With text only:
XML Code: Example of Method Expression With Text Only
<foo:tag value="thistext"/>
Working with Tag Attribute Types
There is a wide variety of expressions which can be used in tag attributes. The type attribute of the tag definition in the TLD will determine what kind of expression is supported as well as how the expression will be evaluated through either immediately or deferred evaluation.

If you intend to create custom tags, you need to specify for each tag in the TLD what kind of expression it accepts. There are three different kinds of tag attributes that accept EL expressions. These are dynamic, deferred value and deferred method. Each of them accept certain types of expressions and have specific type definitions that you will need to add to your TLD. Note that for dynamic attribute type, you cannot use #{} syntax. But this should be obvious since any attribute of this type accepts dynamically-calculated values at runtime. See the table below for more information:

Tutorial:Review of JSP Expression Language for the Web Component Developer Exam-a20-tagattributeselexpressions.jpg
Table: Tag Attributes that Accept EL Expressions

You also have the option of defining an attribute that can accept both dynamic and deferred expressions. In this situation, the tag attribute definition would contain both an rtexprvalue definition set to true and either a deferred-value or deferred-method definition.

Deactivating Expression Evaluation
For reasons of backward compatibility, there are times you might need to deactivate EL evaluation for applications where the patterns used to identify EL expressions are not known and possibly just passed through to output as written. The way to deactivate EL evaluation so that the two key EL expression patterns (i.e. ${} and #{}) are not evaluated is to use one of the following methods discussed below.
Escape the #{ or ${ characters in the page.
In order to do this you should use the \ character as follows:

XML Code: Deactivation of EL in JSP using escape characters
foo text \#{ foo more\${ text
<foo:tag myAttribute="footext\#{more\${text" />
Working With a JSP Property Group

In order to do this allow either the #{ characters to be considered as String literal using the deferred-syntax-allowed-as-literal subelement, or treat all expressions as literals using the el-ignored subelement. This is shown below:

Using deferred-sytax-allowed-as-literal:
XML Code: Deactivation of EL in JSP using deferred-sytax-allowed-as-literal
Using treat all expressions as literals:
XML Code: Deactivation of EL in JSP using el-ignored
Working with the Page Directives

In this approach, you configure the page with a page directive to accept either the #{ characters as String literals with the deferredSyntaxAllowedAsLiteral attribute, or to ignore all EL expressions using the isELIgnored attribute. The valid values of these attributes are true and false. If isELIgnored is true, then EL expressions will be ignored and appear as static text or tag attributes. If false, EL expression will be evaluated by the container if the attribute has set to true the rtexprvalue or it is a deferred expression:

Using deferredSyntaxAllowedAsLiteral attribute:
XML Code: Deactivation of EL in JSP using deferredSyntaxAllowedAsLiteral
<%@page ... deferredSyntaxAllowedAsLiteral="true" %>
Using isELIgnored attribute:
XML Code: Deactivation of EL in JSP using isELIgnored
<%@ page isELIgnored ="true" %>
The default value of isELIgnored for web applications using Servlet 2.4 specification or above is true. For web applications using Servlet 2.3 specification or earlier, the default is false in order to provide backward compatibility.

What are Literal Expressions?

Literal expressions evaluates to the text of the expression. These are always of type String and don’t use the ${} or #{} delimiters. If you are using literal expressions that include the ${} or #{} syntax, you need to escape these characters since they are reserved in web applications.

For creating a composite expression use:
XML Code:

This will result in values that would be strings ${exprA} and #{exprB}.

For string that would be treated as an evaluation expression use:
XML Code:

By using the escape characters \$ and \# this would result in the values being the strings ${exprA} and #{exprB}.

When literal expressions are evaluated, they can be converted to another type. In order to demonstrate the effects of evaluated literal expressions, we have produced the table below to highlight some examples:

Tutorial:Review of JSP Expression Language for the Web Component Developer Exam-a20-literalexpressionexamples.jpg
Table: Literal Expression Examples

With literal expressions you have the option of having them be evaluated immediately or deferred as well as determining whether they can be either value or method expressions. When this evaluation takes place is dependent on where the literal expression is being used. If the literal expression is part of a tag attribute that is defined as accepting a deferred value expression, then the literal expression references a value and is evaluated at that particular point in the lifecycle that is determined by where the expression is used and to what it is referred. For method expressions, the method that is referenced is invoked and returns the specified String literal. This was shown earlier when we discussed method expressions.

How to Resolve Expressions

The unified EL also provides a pluggable API for resolving expressions. This allows application developers to implement their own resolvers to handle expressions not presently supported in unified EL. The main components of this API are the following:
  • ValueExpression class - defines a value expression
  • MethodExpression class - defines a method expression
  • ELResolver class - defines a mechanism for resolving expressions
  • Set of ELResolver implementations - each implementation is responsible for resolving expressions that reference a particular type of object or property
  • ELContext object - for saving state relating to EL resolution, holding references to EL resolvers, and maintaining context objects (i.e. JspContext) that are needed by the underlying technology to resolve expressions

If you are writing JavaServer Faces custom components then you will need to use ValueExpression and MethodExpression. Otherwise unless you intend to write a custom EL resolver, you will not need to use these classes in your development. Let’s look at how expressions are resolved for those interested in creating a custom resolver. You can find more information on creating custom resolvers, by reading this article, “The Unified Expression Language, Ryan Lubke et al”.

Looking at the Expression Evaluation Process

The process of evaluating a value expression that is included in a page starts with the parsing of the value expression during the initial request for the page. At this point a ValueExpression object is created to represent the expression. Next, the getValue method of the ValueExpression is invoked. This method in turn invokes the getValue method of the appropriate resolver. The process is similar during a postback when setValue is called dependent on whether the expression is an lvalue expression.

For a method expression, we find the object that implements the method that is invoked or queried via the BeanELResolver. When the BeanELResolver encounters a method expression during the process of evaluating value expressions, a MethodExpression object is created. Next is the invocation of the MethodExpression’s getMethodInfo method. This will in response invokes the BeanELResolver object’s getValue method. After the resolver completes resolution of an expression, it will set the ELContext’s propertyResolved flag to true in order to avoid other resolvers being consulted.

What are EL Resolvers?

The core of EL is the extensible ELResolver class. Any class implementing ELResolver determines how to resolve expressions that refer to a particular type of object or property. For example, the sequence of calls to a BeanELResolver instance is first to find the base object, controller. Then after finding the object, it is to resolve the property, Airport of the controller object.

XML Code: Expression With Explicit Object Provided
The unified EL has a standard set of resolver implementations. This is shown in the table below:

Tutorial:Review of JSP Expression Language for the Web Component Developer Exam-a20-standardelresolvers.jpg
Table: Standard EL Resolvers

Other resolvers using unified EL are slowly starting to appear. Also, application developers have the ability to add their own ELResolver implementations to support resolution of expressions that are presently not supported by the unified EL as well as register them with an application.

If by chance you do add and register an ELResolver implementation with an application, all of the standard and custom resolvers available to the application are collected in a chain in a specific order. The chain of resolvers is represented by a CompositeELResolver instance. Subsequently, when an expression is encountered, the CompositeELResolver instance will iterate through the list of resolvers until it finds the appropriate one to handle the expression. For JSP applications, the chain of resolvers includes the ImplicitObjectELResolver and the ScopedAttributeELResolver.

Using Implicit Objects

EL provides several predefined objects, called implicit objects, which allow you to access application data that your JSP pages may need. The following table lists these objects and their purposes.

Tutorial:Review of JSP Expression Language for the Web Component Developer Exam-a20-implicitobjects.jpg
Table: Implicit Objects

As we mentioned in the previous section, the JSP 2.1 specification provides for two EL resolvers to handle expressions that reference these objects. These resolvers are:
ImplicitObjectELResolver - this resolver is used for variables that match one of the implicit objects and returns the implicit object. The resolver is specifically for handling expressions with a base of null. An example of this would be in accessing the profile attribute of a implicit object sessionScope. Due to the manner that theImplicitObjectELResolver matches first the implicit object and then the attribute, it will only resolve for the sessionScope. The expression is shown below:

XML Code: Expression With Implicit Object Provided
ScopedAttributeELResolver - this resolver will evaluate a single object that is presently stored in scope. It also only evaluates expressions with a base of null. The ScopedAttributeELResolver looks for an object in all of the scopes until it finds it based on the behavior of PageContext.findAttribute(String). For example in the following example:

XML Code: Scoped Attribute without implicit object provided
The ScopedAttributeELResolver resolver will look for product in the page, request, session, and application scopes and will return the appropriate value. If the product attribute is not found at any scope, a null is returned. A means to avoid this is to for the expression to reference the implicit object by name. In this case, the appropriate object will be returned as well as the particular attribute. An example of this for the PageContext is shown below where the expression is resolved to the PageContext object rather than an existing pageContext attribute that may exist elsewhere:

XML Code: Expression Immediately Scoped to PageContext
Using Operators

In addition to the . and [] operators discussed in Value and Method Expressions, the JSP expression language provides the following operators, which can be used in rvalue expressions only:

Tutorial:Review of JSP Expression Language for the Web Component Developer Exam-a20-operatorsforexpressions.jpg
Table: Operators used in Value and Method Expressions

The order of precedence for options is shown in the next table. In a particular cell, the precedence is from left to right:

Tutorial:Review of JSP Expression Language for the Web Component Developer Exam-a20-operatorprecedence.jpg
Table: Operator Precedence

Using Reserved Words

The following words are reserved for the JSP expression language and should not be used as identifiers.
Tutorial:Review of JSP Expression Language for the Web Component Developer Exam-a20-reservedwords.jpg
Table: Reserved Words

There are a number of these words that are presently not part of the language but as the intention is to add them in the future, their use should be avoided.

What are EL Functions?

The JSP expression language allows you to define a function that can be invoked in an expression. The syntax for a custom EL function is the following:

Java Code: Syntax of EL Function, MyFractal
Although these functions appear similar to method expressions, but are different in a number of ways:
  • Functions are static methods that return a value. Method expressions are non-static, arbitrary public methods on objects.
  • Functions are identified statically at translation time. Method expressions are identified dynamically at runtime.
  • Function parameters and invocations are considered as part of an EL expression. Method expressions only identify a particular method. The invocation of the method is not specified by the EL expression but is specified in the tag attribute definition of the attribute using the method expression.

Working with EL Functions

You can use functions in static text as well as tag attribute values.
In a JSP page, you use a taglib directive to import the tag library that has the function. Then you add the prefix you declared in the directive to the function invocation.
An example is shown where we import the the /fractals library and invoke the fractal function in an expression:

Java Code: Example of Use of EL Function
<%@ taglib prefix="f" uri="/fractals"%>
<c:out "${f:fractal(456, 5)}" >
Here the expression referencing the function uses immediate evaluation syntax. You can also use deferred evaluation syntax to reference a function in an expression as long as the attribute referencing the function can accept deferred expressions. The function will then be invoked whenever the underlying technology using the function determines the time for it’s invocation.

Creating EL Functions

You can use any public static method to define a function. Below is an example that defines a function for generating fractals:

Java Code: Example of EL Function, MyFractal
package com.acme.fractals;
public class MyFractal {

    public static Integer fractal( Integer l1, Integer l2 ) {
        return mandelbrot(l1,l2); 
You then need to define a taglib TLD for your EL function using the function element instead of tag. All you need to do is to map the function name you used in the EL expression to the defining class and function signature in a TLD. In the fractals.tld file of the fractals example maps the fractal function to the class where the function is implementation as well as the signature for the function:

XML Code: Example of TLD file for MyFractal EL Function
    <function-signature>java.lang.Integer fractal( java.lang.Integer,
        java.lang.Integer )</function-signature>
In order to avoid namespace collisions, each function must have a different name.

This chapter showed you how to use the unified expression language. The expression language allows you to modify scoped variables as it suits your program. JSTL can make use of both the new EL as well as the older scriptlet-based expressions. The next article we will explore using Standard Actions.