`

EL Functions 使得static方法直接在el中使用

阅读更多
转载:http://www.seamframework.org/Documentation/CreatingCustomELFunctions



In the WebContent/META-INF/ (JBDS) or view/META-INF/ (seam-gen) create a file called elfunctions.taglib.xml. If the META-INF/ dir does not exist, create it also. The content of elfunctions.taglib.xml should be:



<?xml version="1.0"?>
<!DOCTYPE facelet-taglib PUBLIC "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN" "facelet-taglib_1_0.dtd">
<facelet-taglib>
<library-class>org.el.func.FnLibrary</library-class>
</facelet-taglib>

Create another src package src/facelets with the packagename: org.el.func and add

package org.el.func;

import com.sun.facelets.tag.AbstractTagLibrary;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class FnLibrary extends AbstractTagLibrary {

public final static String Namespace = "http://org.el.func/SeamFunc";

public static final FnLibrary INSTANCE = new FnLibrary();

public FnLibrary() {
super(Namespace);
try {
Method[] methods = SeamFunc.class.getMethods();
for (int i = 0; i < methods.length; i++) {
if (Modifier.isStatic(methods[i].getModifiers())) {
this.addFunction(methods[i].getName(), methods[i]);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
The above will dynamically add any of the static methods in a class called SeamFunc.java to be available in the EL. Now create org.el.func.SeamFunc.java:

package org.el.func;

import org.jboss.seam.core.Expressions;

public class SeamFunc {

public static String concat(String... strings) {
StringBuilder buff = new StringBuilder();
if (strings != null) {
for (String str : strings) {
buff.append(str);
}
}
return buff.toString();
}

public static Object evalEl(String expression) {
String framedExpr = "#{" + expression + "}";
Object value = Expressions.instance().createValueExpression(framedExpr).getValue();
return value;
}

}Now the last piece is to define the location of the elfunctions.taglib.xml in web.xml:

<context-param>
    <param-name>facelets.LIBRARIES</param-name>
    <param-value>
        /META-INF/elfunctions.taglib.xml
    </param-value>
</context-param>Create a test.xhtml page and add:

xmlns:e="http://org.el.func/SeamFunc"and to the body:

#{e:concat('Hello ', 'World!')} / #{e:evalEl('conversation')}These are just two examples of functions, you can create as many as you'd like. The evalEL seems useless, until you realize you can do something like:

#{e:evalEL(e:concat('person', 'Home'))}which correctly resolves the value of the Seam component named personHome.



备注
facelets本身提供了jstl函数,所以jstl中的函数可以使用
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics