Expression Language

Quick TL;DR

<jsp:text>
   Box Perimeter is: ${2*box.width + 2*box.height}
</jsp:text>
  • Referred to as EL

  • Enables the presentation layer (web pages) to communicate with the application logic.

  • Used by both Javaserver Faces & JSP

  • Spring has its own expression language known as Spring Expression Language (SpEL) and is based on the Expression Language foundation albeit offering additional features.

  • Allows page authors to use simple expressions to dynamically access data from JavaBeans components.

  • Can perform the following tasks:

    • Dynamically read application data stored in JavaBeans components, various data structures, and implicit objects

    • Dynamically write data, such as user input into forms to JavaBeans components

    • Invoke arbitrary static and public methods

    • Dynamically perform arithmetic operations

Overview

  • EL supports both immediate and deferred evaluation of expressions.

  • EL defines two kinds of expressions: value expressions and method expressions.

Immediate Evaluation

  • The expression is evaluated and the result is returned as soon as the page is first rendered.

  • Uses the ${} syntax:

    • <fmt:formatNumber value="${sessinoScope.cart.total}"/>

  • Expressions can be used only within template text or as the value of a tag attribute that can accept runtime expressions.

  • Immediate evaluation expressions are always read-only value expressions. For instance, the code snippet above cannot set the total price but can only get the total price from the cart bean.

Deferred Evaluation

  • The expression is evaluated at other phases of a page lifecycle as defined by the technology that is using the expression.

  • Use the #{expr} syntax:

    • <h:inputText id="name" value="#{customer.name}" />

  • For postback requests, the JavaServer Faces implementation evaluates the expression at different phases of the lifecycle, during which the value is retrieved from the request, validated, and propagated to the customer bean.

Value Expressions

  • Can either yield a value or set a value.

  • Can be categorized into rvalue and lvalue expressions:

    • rvalue - Can read data but cannot write to it

    • lvalue - Can both read and write data

  • rvalue expressions are evaluated immediately and use the ${} syntax.

  • Expressions whose evaluation can be deferred use the #{} delimiters and can act as both rvalue and lvalue expressions.

Method Expressions

  • Method expression is used to invoke an arbitrary public method of a bean, which can return a result.

  • Because a method can be invoked during different phases of the lifecycle, method expressions must always use the deferred evaluation syntax.

  • <h: inputText value=#{userNumberBean.userNumber('5')}">

References

Last updated