之前一直没有接触过JSTL自定义标签,由于偶然的机会有幸亲自使用,特总结进行知识的积累和知识的共享。JSTL分自定义函数和自定义标签,在做共性的数据格式处理、数据处理,在前台处理起来比较乏力时,JSTL自定义标签库常常会起到可观的作用。在需要处理共性的html格式时,自定义标签也可以非常方便的解决问题。以我的理解,类似于Spring的AOP机制。下面举两个简单的小例子仅供参考、学习、交流。
1、自定义JSTL函数
1)首先在web.xml中申明,加入以下代码
<jsp-config>
<taglib>
<taglib-uri>my-uri</taglib-uri>
<taglib-location>/WEB-INF/ HtTag.tld</taglib-location>
</taglib>
</jsp-config>
2)新建 HtTag.tld,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" 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">
<tlib-version>1.0</tlib-version>
<short-name>f</short-name> // taglib的名称,也称为前缀
<uri> my-uri </uri> //与web.xml中申明的<taglib-uri>对应
<function> //函数
<description>时间转化</description>
<name>formatTime</name>
<function-class>com.TimeUtil</function-class> //后台对应的处理类
<function-signature>java.lang.String formatTime(long)</function-signature> //类中的处理函数 参数和回调函数要写完整路径
<example>${f:formatTime(date)}</example>
</function>
<tag>//自定义标签
<description>查找字典项</description>
<name>option</name>
<tag-class>com.WriteOption</tag-class> //对应后台处理方法 需继承TagSupport
<body-content>JSP</body-content>
<attribute> //标签属性
<name>nodeKey</name>
<required>true</required> //是否必须有
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>selectKey</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
3)页面引用
<%@taglib prefix="f" uri="my-uri" %>
函数用法:
${f:formatTime(date)}
标签用法:
<select >
<f:option nodeKey="zcddms" selectKey="ttt"></f:option>
</select>
QQ:137879106