How to create a custom EL function to invoke a static method?

前端 未结 1 1249
粉色の甜心
粉色の甜心 2020-11-22 02:36

Im new to JSF 2. My question is related to BalusC\'s answer to this question jsf2 ajax update parts based on request parameters I tried the kickstart code BalusC posted and

1条回答
  •  醉梦人生
    2020-11-22 03:11

    First create a final class with a public static method which does exactly the job you want:

    package com.example;
    
    import java.util.Collection;
    
    public final class Functions {
    
        private Functions() {
            // Hide constructor.
        }
    
        public static boolean contains(Collection collection, Object item) {
            return collection.contains(item);
        }
    
    }
    
    
    

    Then define it as a facelet-taglib in /WEB-INF/functions.taglib.xml:

    
    
        http://example.com/functions
    
        
            contains
            com.example.Functions
            boolean contains(java.util.Collection, java.lang.Object)
        
    
    

    Then familarize Facelets with the new taglib in the existing /WEB-INF/web.xml:

    
        javax.faces.FACELETS_LIBRARIES
        /WEB-INF/functions.taglib.xml
    
    

    (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:

    
    

    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:

         
        com.sun.faces.expressionFactory
        org.jboss.el.ExpressionFactoryImpl   
    
    

    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.

    0 讨论(0)
    提交回复
    热议问题