例如:${math: gcd(10,20) }
步骤:
(1) 撰写函式类别
所有函式都是公开且静态的,编译完成后放在WEB-INF\classes\下即可
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;
}
}
(2) 撰写标签函式描述(Tag Library Descriptor)
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>MathTools</description>
<tlib-version>1.0</tlib-version>
<short-name>SimpleMathTools</short-name>
<uri>/SimpleMathTools</uri>
<function>
<description>GCDTool</description>
<name>gcd</name>
<function-class>
onlyfun.caterpillar.MathTools
</function-class>
<function-signature>
int gcd(int,int)
</function-signature>
</function>
</taglib>
【<function-signature>与<name>对应,<name>是EL呼叫函式所用的名称,而<function-signature>定义了函式的传入参数和返回值。】
(3) 在web.xml中说明class与tld的位置信息
web.xml
【<taglib-url>用来设定使用.tld时的命名空间】
...
<jsp-config>
<taglib>
<taglib-uri>
http://caterpillar.onlyfun.net/
</taglib-uri>
<taglib-location>
/WEB-INF/tlds/mathtools.tld
</taglib-location>
</taglib>
</jsp-config>
...
(4) 在jsp网页中指定标签函式位置与前置文字
elFunction.jsp
【前置文字的作用是当有许多同名函式时,如两个位置的函式库,而当中有相同的函式时,可以根据前置来识别】
<%@taglib prefix="math" uri="http://www.caterpillar.onlyfun.net/"%>
<html>
<body>
Math Tools GCD Test: ${math:gcd(100, 14) }<br>
</body>
</html>