ITEEDU

JSP/Servlet: 自订 EL 函式

对于一些常用的函式,可以将之撰写为一个函式库,之后结合EL中对函式使用的支持即可重复使用该函式,例如您可以这样使用EL函式:

${ math:gcd(10, 20) }

要能够自订EL函式并使用之,我们必须完成四个步骤:

  1. 撰写函式类别
  2. 撰写标签函式描述(Tag Library Descriptor)
  3. 在web.xml中说明class与tld的位置信息
  4. 在JSP网页中指定卷标函式位置与前置文字

一个一个来完成,首先编写下面的程序:

MathTools.java
package onlyfun.caterpillar; 

public class MathTools { 
public static int gcd(int m, int n) { 
int r = 0; 
while(n != 0) { 
r = m % n; 
m = n; 
n = r; 
} 
return m; 
} 

public static double pi() { 
return Math.PI; 
} 
} 

注意所有的函式都是公开且静态的,编译完成之后,将之放置在WEB-INF\classes\下即可,然后撰写标签函式描述(Tag Library Descriptor),这是个XML格式的档案,注意扩展名要是.tld而不是.xml,假设撰写的档名是mathtools.tld:

mathtools.tld
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
web-jsptaglibrary_2_0.xsd" 
version="2.0">
<description>Math Tools</description> 
<tlib-version>1.0</tlib-version> 
<short-name>SimpleMathTools</short-name> 
<uri>/SimpleMathTools</uri>
<function> 
<description>GCD Tool</description> 
<name>gcd</name> 
<function-class>
onlyfun.caterpillar.MathTools
</function-class> 
<function-signature>
int gcd(int,int)
</function-signature>
</function> 
<function> 
<description>PI Tool</description> 
<name>pi</name> 
<function-class>
onlyfun.caterpillar.MathTools
</function-class> 
<function-signature>
double pi()
</function-signature>
</function>
</taglib> 

大部分的卷标光看卷标名就可知道它的作用了(这是XML文件的自描述特性),注意一下<function- signature>,它与<name>对应,<name>是EL呼叫函式时所用的名称,而<function- signature>定义了函式的传入参数与传回值。
接下来在web.xml中添加对.tld与类别档的相关描述:

web.xml
...
<jsp-config> 
<taglib> 
<taglib-uri>
http://caterpillar.onlyfun.net/
</taglib-uri> 
<taglib-location>
/WEB-INF/tlds/mathtools.tld
</taglib-location> 
</taglib> 
</jsp-config> 
... 

<taglib-uri>用来设定使用.tld时的名称空间识别,这个信息在JSP网页中是用来指定将使用哪一个位置的tld文件,接下来直接看看JSP网页中如何使用定义好的EL函式:

elFunction.jsp
<%@taglib prefix="math" 
uri="http://www.caterpillar.onlyfun.net/"%> 
<html> 
<body> 
Math Tools GCD Test: ${ math:gcd(100, 14) }<br> 
Math Tools PI Test: ${ math:pi() } 
</body> 
</html> 

您使用指令元素taglib来指定tld文件的URI位置,并设定使用时的前置文字,前置文字的作用是当有许多同名函式时(例如用了两个位置的函式库,而当中有相同的函式时),可以根据前置文字来识别使用的是哪一个函式。
接下来就是启动Tomcat并执行了,传回的结果是:

<html> 
<body> 
Math Tools GCD Test: 2<br> 
Math Tools PI Test: 3.141592653589793 
</body> 
</html> 

附带一提的是,并不一定要在web.xml中添加对.tld与类别档的相关描述,如果没有这个步骤的话,在JSP网页中直接指定.tld的实体位置也是可以的: 

<%@taglib prefix="math" uri="/WEB-INF/tlds/mathtools.tld"%>

在web.xml中定义.tld的信息是为了管理的方便,如果不定义,则每次更动.tld档案的位置或名称,则必须修改每一个JSP网页,如果有在 web.xml档中定义,则更动.tld档案的位置或名称后,只要修改web.xml中的定义即可。