1.创建一个HelloTag.java, 注意不要写裸体类
package mytag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class HelloTag extends SimpleTagSupport{
public void doTag() throws JspException, IOException {
this.getJspContext().getOut().write("Hello!");
}
}
2.写一个jsp文件,用来测试testtag.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ taglib uri="/helloworldtaglib" prefix="mytag" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
<mytag:helloworld/>
</body>
</html>
3.在web-inf 目录下创建一个tld文件,取名为 helloworld.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">
<tlib-version>2.0</tlib-version>
<short-name>mytag</short-name>
<uri>/helloworldtaglib</uri>
<tag>
<name>helloworld</name>
<tag-class>mytag.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
OK!测试一下,自己体会其中的原理吧!