在EL表达式中使用参数

时间:2009-09-28 14:45:40

标签: jsf facelets

我需要在EL表达式(使用JSF)中使用带有参数的函数,如下所示:

<h:outputText value="#{object.test(10)}" ></h:outputText>

但它不起作用。

我在网上看到用JSF做这件事是不可能的。我在JSF中使用facelet。

有人知道怎么做吗?

感谢。

4 个答案:

答案 0 :(得分:4)

您可以在自己的taglib中将该方法作为自定义facelet函数提供。该方法必须是静态的,因此如果您尝试在特定bean上调用方法,则必须将bean和参数传递给静态facelet函数。在你的情况下,它会像

<h:outputText value="#{my:doStuff(object,10)}" ></h:outputText>

并且你的facelet功能将是

public static String doStuff( MyType o, int param )
{
    return o.test( param );
}

然后,使用the facelets docbook中的信息,您将在taglib.xml文件中定义您的函数。

这不是最漂亮的解决方案,特别是如果你打算这么做,但我相信EL的下一个版本(在java EE 6中)将允许在某些情况下使用参数。

修改:有关el的下一版本中参数化方法调用的一些信息,请参阅Ryan Lubke's Blog

答案 1 :(得分:2)

我找到了一个悲伤的解决方案,但它正在发挥作用。我重载这样的地图:

new AbstractMap<Integer, String>()
    {

        @Override
        public Set<Entry<Integer, String>> entrySet()
        {
            return null;
        }

        @Override
        public String get(final Object arg0)
        {
            Integer keywordDb = (Integer)arg0;
            GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("keywordDb", keywordDb.toString());
            params.put("month", new Integer(cal.get(Calendar.MONTH) + 1).toString());
            params.put("year", new Integer(cal.get(Calendar.YEAR)).toString());
            DataAnalyzeManager manager = new DataAnalyzeManager();
            manager.setEm(modelPosition.getEm());
            DataAnalyze data = manager.findDataByParams(params, modelPosition.getSite(), false, DataAnalyzeManager.VISITBYMONTHBYKEYWORD);
            if (data != null)
                return data.getDataInt().toString();
            return "0";
        }
    };

因此,我可以在我的JSF中做到这一点:

#{homePositionController.visitByMonth[keyword.keyword.keywordDb]}

我的功能已经执行。

答案 2 :(得分:0)

您可能必须在页面顶部放置<%@ page isELIgnored ="false" %> 。阅读更多here.默认是忽略el表达式。您在JSF中使用的是什么版本的JSP规范?如果您正在使用带有JSP的JSF 2&lt; 2.1你会遇到问题。

此外,您使用的是哪个版本的el?你不能用旧版本传递方法参数。

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

答案 3 :(得分:0)

有几种方法可以做到这一点,你可以使用JBoss EL表达式实现它们支持带参数的方法调用检查Seam,或者使用@digitaljoel建议的类似方法。 这就是我为此目的创建的,您可以调用静态和静态方法,而不是一个很好的解决方案,但它可以完成这项工作。

<c:if  test="#{t:call(null, '@Util.SecurityUtility', 'isPanelWorkbookEnabledForUser','')}">
      Hello Panel    
  </c:if>

@Util只是com.mycomp.util的别名

示例2

<c:if test="#{item != null and  t:call(item, 'java.lang.String', 'indexOf', t:params(t:param('flash-alert',''))) == 0}">                
    #{t:call(session, 'org.apache.catalina.session.StandardSessionFacade', 'removeAttribute', t:params(t:param(item,'')))}      
</c:if>

Syxtax java.lang.Object调用(java.lang.Object,java.lang.String,java.lang.String,java.lang.Object []) 其中Object是对象,我们想要调用方法,String是方法名称,Object []是要传递的参数。

t:call,t:params,t:param是project-taglib.xml中定义的函数,因此

    <function>
    <function-name>call</function-name>
    <function-class>util.Functions</function-class>
    <function-signature>java.lang.Object call(java.lang.Object, java.lang.String, java.lang.String, java.lang.Object[])</function-signature>
</function>
<function>
    <function-name>param</function-name>
    <function-class>.util.Functions</function-class>
    <function-signature>java.lang.String param(java.lang.Object, java.lang.String)</function-signature>
</function> 

<function>
    <function-name>params</function-name>
    <function-class>util.Functions</function-class>
    <function-signature>java.lang.Object[] params(java.lang.String)</function-signature>
</function> 

这是实施

package mycompany.web.util;

import java.beans.XMLDecoder; import java.beans.XMLEncoder; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.StringWriter; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Date; import java.util.HashMap; import java.util.List;

import javax.el.MethodNotFoundException;

公共类函数{

private  static HashMap<String, String> alliasMap;
static{
    alliasMap=new HashMap<String, String>();
    alliasMap.put("@DateUtil", "com.americanbanksystems.compliance.util.DateUtil");
    //Match anything following the dot(.)
    alliasMap.put("@Util.*", "com.americanbanksystems.compliance.util");

    alliasMap.put("@Application.*", "com.americanbanksystems.compliance.application");

}




public static String param(Object obj, String cls) {    
    //make sure that passed in object is not null
    if(obj==null){
        obj="";
    }

    ByteArrayOutputStream baut=new ByteArrayOutputStream();
    XMLEncoder encoder=new XMLEncoder( baut );
    //Bug in the JDK
    //http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=c993c9a3160fd7de44075a2a1fa?bug_id=6525396
    if(obj instanceof java.sql.Timestamp){
        Date o = new Date(((java.sql.Timestamp)obj).getTime());
        obj=o;
    }       
    //Checking if this is possible 
    if(String.class.isAssignableFrom(obj.getClass())){
        //removed trailing +" " because it was causing indexOf return invalid value
        //Unknown side effects
        obj=FacesUtil.get(obj.toString());          
    }
        encoder.writeObject( obj );
    encoder.close();
    return new String(baut.toByteArray());
}

private static Object decode(String str){
    ByteArrayInputStream bais=new ByteArrayInputStream(str.getBytes());
    XMLDecoder decoder=new XMLDecoder(bais);
    return decoder.readObject();
}

public static Object[] params(String str){
    // (?<=</java>)\s*(?=<?)
    String[] obj=str.split("(?<=</java>)\\s*(?=<?)");
    Object[] results=new Object[obj.length];
    for(int i=0;i<obj.length;i++){
        results[i]=decode(obj[i]);
    }
    return results;
}


@SuppressWarnings("unchecked")
public static Object call(Object owningObject, String qualifiedClassname, String methodName, java.lang.Object... methodArguments) {
    if (null == methodName || methodName.equals("")) {
        throw new IllegalArgumentException("Method name can't be null or empty");
    }
    if (null == methodArguments) {
        methodArguments = new Object[0];
    }

    //Check for aliases 
    if(qualifiedClassname.indexOf("@")>-1){
        String subpackage=qualifiedClassname;
        String originalClass=qualifiedClassname;
        //Split at the dot
        boolean isPackageAllias=false;
        String[] sp=subpackage.split("\\.");    
        if(sp.length>1){
            subpackage=sp[0]+".*";
            isPackageAllias=true;
        }
        if(alliasMap.containsKey(subpackage)){
            String value = alliasMap.get(subpackage);
            if(isPackageAllias){
                qualifiedClassname=subpackage.replace(sp[0], value);
                qualifiedClassname=qualifiedClassname.replace(".*", originalClass.replace(sp[0],""));
            }else{
                qualifiedClassname=value;
            }
        }else{
            throw new IllegalArgumentException("Allias name '"+qualifiedClassname+"' not found");
        }
    }
    Class clazz;
    try {
        clazz = Class.forName(qualifiedClassname);
        //Find method by methodName,Argument Types
        Class[] argumentTypes=new Class[methodArguments.length];    

        for(int i=0;i<methodArguments.length;i++){
            argumentTypes[i]=methodArguments[i].getClass();
            //Check if the passed in method argument is a string and if its represented as unicode char             
            //if it is then convert it into a char and reassign to the original parameter
            //example 1:  \u0022 == "
            //example 2:  \u0027 == '
            // Reason for this functionality is that we can't pass " and ' from within t:call method
            if (argumentTypes[i] == String.class && methodArguments[i].toString().indexOf("\\u") > -1) {
                String arg = methodArguments[i].toString();
                arg = arg.substring(2, arg.length());
                try {
                    int outchar = Integer.parseInt(arg, 16);
                    if (Character.isDefined(outchar)) {
                        methodArguments[i] = String.valueOf((char) outchar);
                    }
                } catch (NumberFormatException nfe) {
                    // Suppress error and continue assuming this is a regular string
                }
            }
        }

        Method methodToInvoke = null;
        try{
            methodToInvoke  = clazz.getMethod(methodName, argumentTypes);
        }catch(NoSuchMethodException nsm){//Find by method name/ argument count
            for (Method method : clazz.getMethods()) {
                if (method.getName().equals(methodName)  && method.getParameterTypes().length == methodArguments.length) {
                    if (null == owningObject) {
                        owningObject = clazz.newInstance();
                    }
                    methodToInvoke=method;
                    break;
                }
            }
        }

        if(methodToInvoke!=null){                               
            return methodToInvoke.invoke(owningObject, methodArguments);
        }else{
            throw new InstantiationException("method not found :" + methodName);    
        }

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    }
    return null;
}


public static void main(String[] arg) {
    // StringBuffer buff=new StringBuffer();
    // buff.append("Gregs init");
    // Functions.call(java.lang.Class<T>, T, java.lang.String, java.lang.String, java.lang.Object...)
    /*
     * Functions.call(StringBuffer.class, buff, "java.lang.StringBuffer","append"," Init ");
     * Functions.call(StringBuffer.class, buff, "java.lang.StringBuffer","append"," greg ");
     * System.out.println("output="+ buff);
     */

    //#{t:call(null, ".util.DateUtil", "normalizeDate", t:parametize(editRiskActionPlan.riskActionPlan.completionDate,",","java.lang.Object"))}
//  c(call(null, "util.DateUtil", "normalizeDate", new Date()));

    //  #{t:parametize(editRiskActionPlan.riskActionPlan.completionDate,",","java.lang.Object")}
    //parametize((new Date()).toString(),",","java.lang.Object");
    Date a=new Date();

    Date b=new Date();

    String rawString=param((Date)b, Date.class.toString() );                    
    //System.out.println(rawString);

    //Replaced=#{t:call("Gregs ' car", 'java.lang.String', 'replace', t:params( parameter ))}

    String paramA=param("\\u0027","");
    String paramB=param("\\u0022","");
    String params=paramA+paramB;
    String in="I need to ' have a replaced single quote with double";
    String out=(String)call(in, "java.lang.String", "replace", params(params));

    System.out.println(out);


    /*
    Object[] obj=params(rawString);
    for(Object o:obj){
        System.out.println(o);
    }
    //c(call(null, "@DateUtil", "normalizeDate", obj));

    */

}

}

我希望这有帮助,顺便说一下,这是从我的项目中复制/粘贴的,所以不确定我是否遗漏了任何东西。