带标签体自定义标签
-
步骤:和前面的没区别
-
创建自定义标签类:
package taglibclass;
import java.io.IOException;
import java.util.Collection;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class BodyTag extends SimpleTagSupport {
private String collection;
private String item;
@SuppressWarnings("unchecked")
@Override
public void doTag() throws JspException, IOException {
Collection<String> itemList = (Collection<String>)getJspContext().getAttribute(collection);
for (String string : itemList) {
getJspContext().setAttribute(item, string);
getJspBody().invoke(null);
}
}
public String getCollection() {
return collection;
}
public void setCollection(String collection) {
this.collection = collection;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
}
- 配置自定义标签
<tag>
<name>bodyTag</name>
<tag-class>taglibclass.BodyTag</tag-class>
<!--有属性的自定义标签相比,只是该标签值由empty改为scriptless-->
<body-content>scriptless</body-content>
<attribute>
<name>collection</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>item</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
- 使用标签:
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="mytaglib/mytag" 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=UTF-8">
<title>bodyTag</title>
</head>
<body>
<h2>带标签体的标签-迭代器标签</h2>
<%
List<String> a = new ArrayList<String>();
a.add("java");
a.add("hello taglib");
a.add("sysker");
pageContext.setAttribute("a", a);
%>
<table border="1">
<mytag:bodyTag collection="a" item="item">
<tr>
<td>${pageScope.item}</td>
</tr>
</mytag:bodyTag>
</table>
</body>
</html>