自定义标签的步骤:
- 定义类和方法(方法必须是public static)
- 编写自定义 tld文件,放在web-inf目录下
- 在jsp中采用taglib指令引用自定义函数库
- 调用${前缀:函数名}
一下是具体的使用
我定义的是一个读取Clob数据类型的类
public class readClob {
public static String read(Clob clob) throws Exception{
String str = null;
InputStream stream = clob.getAsciiStream();
int len = (int)clob.length();
byte[] b = new byte[len];
int i;
while(-1 != (i = stream.read(b, 0, b.length))) {
stream.read(b, 0, i);
}
str = new String();
return str;
}
}
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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>JSTL 1.1 functions library</description>
<display-name>myFunction</display-name>
<tlib-version>1.1</tlib-version>
<short-name>my</short-name>//(prefix="my")
<uri>http://www.hdax.com/functions</uri>//(url="")
<function>
<name>read</name>//方法名
<function-class>utils.readClob</function-class>//所在的包和类
<function-signature>java.util.String read(java.sql.Clob)</function-signature>
</function>
</taglib>
jsp页面里<%@ taglib uri="http://www.hdax.com/functions" prefix="my" %>
实际调用
<tr>
<td align="left">${my:read(article.content) }</td>
</tr>