El中調用靜態方法


最近在項目中遇到需要調用靜態方法的問題,形如:

<c:forEach items="beans" var="bean">
    <p>總數:${com.example.Tools.getTotal(bean.nums)}</p>
</c:forEach>

不過上面的代碼不能通過編譯,只能尋求其他辦法。經過查閱各種文檔,找到了3種解決辦法。

1,直接為Bean創建一個get方法

public double getTotal(){
       return com.example.Tools.getTotal(nums);
}

然后在EL中直接使用:

總數:${bean.total}

2,將Tools#getTotal創建為一個EL function。首先創建一個/WEB-INF/my.tld文件:

<?xml version="1.0" encoding="UTF-8" ?>
<taglib 
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
    version="2.1">

    <display-name>Custom Functions</display-name>    
    <tlib-version>1.0</tlib-version>
  
<short-name>my</short-name><!--short-name元素可不寫 --> <uri>http://example.com/functions</uri> <function> <name>calculateTotal</name> <function-class>com.example.Tools</function-class> <function-signature>double getTotal(double[])</function-signature> </function> </taglib>

然后在web.xml中定義uri和tld文件路徑的映射:

<jsp-config>    
    <taglib>    
        <taglib-uri>http://example.com/functions</taglib-uri>    
        <taglib-location>/WEB-INF/my.tld</taglib-location>    
    </taglib>    
</jsp-config>   


接着在要使用的jsp頭部引入該taglib:

<%@ taglib uri="http://example.com/functions" prefix="my" %> 

其中uri對應web.xml中的taglib-uri。最后就可以在EL中使用該函數了:

<c:forEach items="beans" var="bean">
    <p>總數:${my:calculateTotal(bean.nums)}</p>
</c:forEach>

 

3,使用Spring的SpEL:

jsp頭部引入:

<%@taglib prefix="s" uri="http://www.springframework.org/tags" %>

使用:

<c:forEach items="beans" var="bean">
    <s:eval expression="T(com.example.Tools).getTotal(bean.nums)" var="total" />
    <p>總數:${total}</p>
</c:forEach>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM