一、写一个标签处理类
package tw.com.javaword.ch15;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
public class Hello extends TagSupport{
public int doStartTag(){
try{
JspWriter out = pageContext.getOut();
out.println( "Hello World Using Tag Library" );
}catch( Exception e ){
System.out.println( "Hello Tag Error : " + e );
}
return ( SKIP_BODY );
}
}
二、定义 Tag Library Descriptor ( tld )
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<!-- a tag library descriptor -->
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>Mytaglib</short-name>
<uri></uri>
<description>My Taglib by JavaWorld.com.tw</description>
<tag>
<name>Hello</name>
<tag-class>tw.com.javaword.ch15.Hello</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
三、使用标签
<%@ page contentType="text/html;charset=GB2312" %>
<%@ taglib uri="/WEB-INF/tlds/MyTaglib.tld" prefix="mytag" %>
<html>
<body>
<mytag:Hello />
</body>
</html>
当然我们可以在 web.xml 中增加如下内容
<taglib>
<taglib-uri>Taglib</taglib-uri>
<taglib-location>/WEB-INF/tlds/MyTaglib.tld</taglib-location>
</taglib>
然后将 <%@ taglib uri="/WEB-INF/tlds/MyTaglib.tld" prefix="mytag" %>
改成 : <%@ taglib uri="Taglib" prefix="mytag" %>