首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

JSP EL 函式庫開發完整指南

     編輯:Java 相關知識

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 解析器找不到。

二、定義 TLD 檔 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>

四、JSP 頁面使用

<%@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> 擴充函式庫(如日期格式化、字串截斷、金額格式化)。
  • Tomcat 7+ 可直接將 TLD 放入 META-INF 免 web.xml 註冊。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved