1.创建一个tld文件
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
<description>myJSTL library</description>
<display-name>myJSTL</display-name>
<tlib-version>1.0</tlib-version>
<short-name>ch</short-name><!--标签名-->
<uri>http://run.com/mytld</uri>
<tag>
<description>mytld</description>
<name>say</name><!--方法名-->
<tag-class>com.linkcc.Action.MytldClass</tag-class><!--这里写上实现类路径-->
<body-content>empty</body-content>
<attribute> <!--属性-->
<description>
Name of say
</description>
<name>info</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute> <!--属性-->
<description>
Name of say
</description>
<name>qty</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
2.编写java类,在doTag方法中添加处理逻辑
public class MytldClass extends SimpleTagSupport{
//类要符合javabean规范,并且属性值与tld中写的属性值要相对
private String info;
private int qty;
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
//初始化变量后,执行doTag程序
@Override
public void doTag() throws JspException, IOException {
PageContext pc = (PageContext)getJspContext();
JspWriter out =pc.getOut();
for(int i= 0;i<qty;i++)
{
out.println("info<br/>");
}
}
}
3.在页面中使用
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="ch" uri="http://run.com/mytld" %><!--这里导入Tag的uri和Tag的名称-->
<html>
<head>
<title></title>
</head>
<body>
<ch:say info="Hello" qty="100"></ch:say>
</body>
</html>