JSP 2.0 引入 Expression Language (EL) 並支援自訂函式,讓視圖層能直接呼叫 Java 靜態方法。本文以 Tomcat 6 為例,示範從撰寫函式類、定義 TLD、註冊 web.xml 到頁面使用的完整流程。
檔案:WEB-INF/classes/el/ELFunction.java
package el;
public class ELFunction {
public static String toUpper(String str) {
return str.toUpperCase();
}
}
關鍵點:方法必須為 public static,否則 EL 解析器找不到。
el.tld位置:WEB-INF/tlds/el.tld
<?xml version='1.0' encoding='GBK'?>
<taglib xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://java.sun.com/xml/ns/j2ee https://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0" xmlns="https://java.sun.com/xml/ns/j2ee">
<tlib-version>1.0</tlib-version>
<short-name>fc</short-name>
<uri>https://wintys/el</uri>
<function>
<name>toUpper</name>
<function-class>el.ELFunction</function-class>
<function-signature>java.lang.String toUpper(java.lang.String)</function-signature>
</function>
</taglib>
web.xml 註冊 TLD<taglib>
<taglib-uri>https://wintys/el</taglib-uri>
<taglib-location>/WEB-INF/tlds/el.tld</taglib-location>
</taglib>
<%@page contentType="text/html;charset=GBK"%>
<%@taglib uri="https://wintys/el" prefix="myfun" %>
EL Function:<br/>
${myfun:toUpper("abcde")}
重新啟動 Tomcat,瀏覽 ELFunction.jsp,輸出:
EL Function:
ABCDE
<function> 擴充函式庫(如日期格式化、字串截斷、金額格式化)。META-INF 免 web.xml 註冊。