EL function in JSF (Expression Language in JSF)
Hi guys today we will talk about EL function in JSF (Java Server Faces) ,then w’ll show how to create a custom EL function in JSF .
EL Expression Language is a scripting language or mechanism for enabling the presentation layer (web pages) to communicate with the application logic, EL is used by several Java EE related technologies such as JSF (Java Server Faces), JSP (JavaServer Pages) represented as implementation of this scripting language EL by those tech (e.g. in JSF it’s called Unified EL), also i want to note that El seen adoption within many Java frameworks such as Spring with SpEL and JBoss with JBoss EL .
In this article, we’ll create our custom function using Unified EL which is an implementation of EL scripting language in JSF technology
First create a final
class with a public static
method which does exactly the job you want:
Then define it as a facelet-taglib in /WEB-INF/functions.taglib.xml:
package com.example;
import java.util.Collection;
public final class Functions {
private Functions() {
// Hide constructor.
}
public static boolean contains(Collection<Object> collection, Object item) {
return collection.contains(item);
}
}
Then familarize Facelets with the new taglib in the existing /WEB-INF/web.xml
:
<context-param>
<param-name>javax.faces.FACELETS_LIBRARIES</param-name>
<param-value>/WEB-INF/functions.taglib.xml</param-value>
</context-param>
(note: if you already have the javax.faces.FACELETS_LIBRARIES
definied, then you can just add the new path semicolon separated)
Then define it in the Facelets XHTML file as new XML namespace:
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:func="http://example.com/functions"
...
>
Finally you can use it as intended:
rendered="#{func:contains(bean.panels, 'u1')}"
As a completely different alternative, you can also include JBoss EL in your project. It works on Tomcat 6.0 and you’ll be able to invoke non-getter methods in EL. Drop jboss-el.jar file in /WEB-INF/lib
and add the following to your web.xml
:
<context-param>
<param-name>com.sun.faces.expressionFactory</param-name>
<param-value>org.jboss.el.ExpressionFactoryImpl</param-value>
</context-param>
Since EL 2.2 there’s another approach: create an @ApplicationScoped
bean with methods in turn referring to those static functions. See also a.o. Utility methods in application scoped bean.
Resources :
Oracle, Baeldung, Stackoverflow .
Comments