利用SimpleTagSupport对标签体的内容循环三次
自定义标签类的编写:
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
public class MySimpleTagIterator extends SimpleTagSupport {
private int num;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
@Override
public void doTag() throws JspException, IOException {
JspFragment jspFragment = getJspBody();
for(int i=0;i<3;i++) {
jspFragment.invoke(null);
}
}
}
继承SimpleTagSupport 类,使用SimpleTagSupport 类的doTag方法。jspFragment.invoke(null)把标签体的内容直接输出。利用for循环对内容输出三次。
对编写的标签进行配置:
<?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>我的自定义简单迭代器标签</description>
<tlib-version>1.0</tlib-version>
<short-name>MySimpleTag</short-name>
<uri>http://www.wpcsimple.com</uri>
<!-- 自定义标签的相关信息 -->
<tag>
<description>我的自定义简单迭代器标签</description>
<name>mySimpleTag</name>
<tag-class>org.wpc.tag.MySimpleTagIterator</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>num</name>
<required>true</required>
</attribute>
</tag>
</taglib>
以上内容中:
<description>我的自定义简单迭代器标签</description>
<tlib-version>1.0</tlib-version>
<short-name>MySimpleTag</short-name>
<uri>http://www.wpcsimple.com</uri>
以上代码是对自定义标签的配置文件的一个描述:
<description>对标签内容的描述</description>
<tlib-version>标签的版本信息</tlib-version>
<short-name>标签文件名</short-name>
<uri>对标签文件的引用url</uri>
对编写的标签的描述:
<tag>
<description>标签的描述</description>
<name>标签名</name>
<tag-class>引用的类</tag-class>
<body-content>标签体类型(scriptless简单标签能使用JSP)</body-content>
<attribute>
<name>传入的属性名</name>
<required>对属性的强制要求(true、false)</required>
</attribute>
</tag>
标签的配置文件后缀为.tld。如图:
自定义标签的使用:
<%@taglib prefix="wpcsimple" uri="http://www.wpcsimple.com" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<wpc:myTag num="3">hello</wpc:myTag>
<wpc:myToUpperCase>hello</wpc:myToUpperCase>
<wpcsimple:mySimpleTag num="3">nihaoa!</wpcsimple:mySimpleTag>
</body>
</html>
对标签体的引入:
<%@taglib prefix="wpcsimple" uri="http://www.wpcsimple.com" %>
对标签体的使用:
<wpcsimple:mySimpleTag num="3">nihaoa!</wpcsimple:mySimpleTag>