baeldung - Coding and Testing Stuff: Introduction to JSF Expression Language 3.0

Datetime:2016-08-22 23:35:26          Topic: Test Engineer           Share

The Master Class of " Learn Spring Security " is live:

>> CHECK OUT THE COURSE

1. Overview

In this article, we’ll look at the latest features, improvements and compatibility issues of Expression Language, version 3.0 (EL 3.0).

This is the latest version as at the time of this writing and ships with more recent JavaEE application servers (JBoss EAP 7 and Glassfish 4 are good examples that have implemented support for it).

The article is focused on the developments in EL 3.0 only – to learn more about Expression Language in general, read theEL version 2.2 article first.

2. Prerequisites

The examples shown in the article have been tested against Tomcat 8 as well. In order to use EL3.0, you must add the following dependency:

<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>3.0.0</version>
</dependency>

You can always check the Maven repository for the latest dependency by following this link .

3. Lambda Expressions

The latest EL iteration provides very robust support for lambda expressions. Lambda expressions were introduced into Java SE 8, but support for it in EL comes with Java EE 7.

The implementation here is full-featured, allowing for a great deal of flexibility (and some implied risk) in EL use and evaluation.

3.1. Lambda EL Value Expressions

Basic use of this functionality allows us to specify a lambda expression as the value type in an EL value expression:

<h:outputText id="valueOutput" 
  value="#{(x->x*x*x);(ELBean.pageCounter)}"/>

Extending from that, one can name the lambda function in EL for reuse in compound statements, just like you would in a lambda expression in Java SE. Compound lambda expressions can be separated by a semi-colon ( ; ):

<h:outputText id="valueOutput" 
  value="#{cube=(x->x*x*x);cube(ELBean.pageCounter)}"/>

This snippet assigns the function to the cube identifier, which is then available for reuse immediately.

3.2. Passing Lambda Expressions to the Backing Bean

Let’s take this a little further: we can get a lot of flexibility by encapsulating logic in an EL expression (as a lambda) and passing it to the JSF backing bean:

<h:outputText id="valueOutput" 
  value="#{ELBean.multiplyValue(x->x*x*x)}"/>

This now allows us to process the lambda expression whole as an instance of javax.el.LambdaExpression :

public String multiplyValue(LambdaExpression expr){
    String theResult = (String) expr.invoke(FacesContext
      .getCurrentInstance().getELContext(), pageCounter);
    return theResult;
}

This is a very powerful feature that allows:

  • A clean way to package logic, providing for a very flexible functional programming paradigm. The backing bean logic above could be conditional based on values pulled in from different sources.
  • An easy way to introduce lambda support in pre-JDK 8 code-bases, that might not be ready to upgrade.
  • A powerful tool in using the new Streams/Collections API.

4. Collections API Enhancements

The support for the Collections API in earlier versions of EL were somewhat lacking. EL 3.0 has introduced major API improvements in its support for the Java Collections, and just like the lambda expressions, EL 3.0 provides JDK 8 Streaming support within Java EE 7.

4.1. Dynamic Collections Definition

New in 3.0, we can now dynamically define ad-hoc data structures in EL:

  • Lists:
<h:dataTable var="listItem" value="#{['1','2','3']}">
       <h:column id="nameCol">
           <h:outputText id="name" value="#{listItem}"/>
       </h:column>
   </h:dataTable>
  • Sets:
<h:dataTable var="setResult" value="#{{'1','2','3'}}">
    ....
   </h:dataTable>

        Note: As with normal Java Sets, the order of the elements is unpredictable, when listed

  • Maps:
<h:dataTable var="mapResult" 
     value="#{{'one':'1','two':'2','three':'3'}}">

Tip : A common mistake in textbooks (and even in the official documentation from Oracle ) when defining dynamic maps uses double quotes (“) instead of single quote for the Map key – it’s  going to result in an EL compilation error.

4.2. Advanced Collection Operations

With EL3.0, there is support for an advanced query semantics that combines the power  of lambda expressions, the new streaming API and SQL-like operations like joins and grouping. We won’t cover these in this article as these are advanced topics. Let’s look at a sample to demonstrate its power:

<h:dataTable var="streamResult" 
  value="#{['1','2','3'].stream().filter(x-> x>1).toList()}">
    <h:column id="nameCol">
        <h:outputText id="name" value="#{streamResult}"/>
    </h:column>
</h:dataTable>

The table above will filter a backing list using the lambda expression passed

<h:outputLabel id="avgLabel" for="avg" 
   value="Average of integer list value"/>
 <h:outputText id="avg" 
   value="#{['1','2','3'].stream().average().get()}"/>

The output text avg will compute the average of the numbers in the list. Both of these operations are null-safe by way of the new  Optional  API (another improvement on previous versions).

Remember that support for this doesn’t require JDK 8, just JavaEE 7/EL3.0. What this means is that you’re able to do most of the JDK 8 Stream operations in EL, but not in the backing bean Java code.

Tip:   You can use the JSTL  <c:set/>  tag to declare your data structure as a page-level variable and manipulate that instead throughout the JSF page:

<c:set var='pageLevelNumberList' value="#{[1,2,3]}"/>

You can now refer to “#{pageLevelNumberList}” throughout the page like it were a bona-fide JSF component or bean. This allows a significant amount of reuse throughout the page

<h:outputText id="avg" 
  value="#{pageLevelNumberList.stream().average().get()}"/>

5. Static Fields and Methods

There was no support for static field, method or Enum access in previous versions of EL. Things have changed.

First we have to manually import the class containing the constants into the EL context. This is ideally done as early as possible. Here we’re doing it in the @PostConstruct  initializer of the JSF managed bean (A ServletContextListener  is also a viable candidate) :

@PostConstruct
 public void init() {
     FacesContext.getCurrentInstance()
       .getApplication().addELContextListener(new ELContextListener() {
         @Override
         public void contextCreated(ELContextEvent evt) {
             evt.getELContext().getImportHandler()
              .importClass("com.baeldung.el.controllers.ELSampleBean");
         }
     });
 }

Then we define a String constant field (or an Enum if you choose) in the desired class:

public static final String constantField 
  = "THIS_IS_NOT_CHANGING_ANYTIME_SOON";

After which we can now access the variable in EL:

<h:outputLabel id="staticLabel" 
   for="staticFieldOutput" value="Constant field access: "/>
 <h:outputText id="staticFieldOutput" 
   value="#{ELSampleBean.constantField}"/>

Per the EL 3.0 specification, any class outside of java.lang.* needs to be manually imported as shown. It’s only after doing this that the constants defined in a class are available in EL. The import is ideally done as part of the initialization of the JSF runtime.

A few notes are necessary here:

  • The syntax requires that the fields and methods be  public, static (and  final  in the case of methods)
  • The syntax changed between the initial draft of the EL 3.0 specification and the release version. So in some textbooks, you might still find something that looks like:

    T(YourClass).yourStaticVariableOrMethod

    This won’t work in practice (a design change to simplify the syntax was decided late into the implementation cycle)

  • The final syntax that was released still came out with a bug as seen in Glassfish   (and a similar bug in Tomcat 8.0.9 ). It’s important to be running the latest versions of these.

6. Conclusion

We’ve examined some of the highlights in the latest EL implementation. Major improvements were made to bring cool new features like lambda and streams flexibility to the API.

With the flexibility that we now have in EL, it’s important to remember one of the design objectives of the JSF framework: clean separation of concerns with the use of the MVC pattern.

So it’s worth noting that the latest improvements to the API may open us up to anti-patterns in JSF, because EL now has the capability to do real business logic – more so than before. And so it’s definitely important to have that in mind during a real-world implementation, to make sure responsibilities are neatly separated.

And of course, the examples from the articles can be found in GitHub .





About List