标签处理器类(自定义标签)ForEach

该处理器的 父类  javax.servlet.jsp.tagext.SimpleTagSupport

public class ForEach extends SimpleTagSupport {
private Collection<?> items;
public void setItems(Collection<?> items) {
this.items = items;
}
private String var;
public void setVar(String var) {
this.var = var;
}
@Override
public void doTag() throws JspException, IOException {
//遍历items集合
if(items!=null){
for(Object obj:items){
//*把正在遍历的对象放入PageContext中 键,var 值,正在遍历的对象
getJspContext().setAttribute(var, obj);
//直接输出到页面上
getJspBody().invoke(null);
}
}
}

}

jsp页面里面模拟数据

<%
List<TestTag> tg = new ArrayList<TestTag>();
tg.add(new TestTag(1, "AAA"));
tg.add(new TestTag(2, "BBB"));
tg.add(new TestTag(3, "CCC"));
tg.add(new TestTag(4, "DDD"));
request.setAttribute("tg", tg);
%>

<!-- 使用标签库foreach -->
<c:forEach items="${requestScope.tg }" var="abc">
${abc.id}--${abc.name}<br>
</c:forEach>

<!-- 使用自定义标签foreach -->
<wlc:ForEachTag items="${requestScope.tg }" var="abc">
${abc.id}--${abc.name}<br>
</wlc:ForEachTag>

tld文件声明

<tag>
<name>ForEachTag</name>
<tag-class>cn.stud.wlc.tag.ForEach</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>items</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>var</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
原文地址:https://www.cnblogs.com/wlc297984368/p/5431638.html