简单标签是简化第四节;
iterateSimple.jsp
<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="please" uri="/WEB-INF/lang.tld"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<%
List people = new ArrayList();
people.add("王小二2");
people.add("思思光2");
people.add("草泥马2");
pageContext.setAttribute("people", people);
%>
</head>
<body>
<please:iterate items="people" var="p">
<h2>${p }</h2>
</please:iterate>
</body>
</html>
IterateSimpleTag.java
package com.lang.tag;
import java.util.List;
import java.io.IOException;
import java.util.Iterator;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import javax.servlet.jsp.tagext.TagSupport;
public class IterateSimpleTag extends SimpleTagSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private String var;
private String items;
public String getVar() {
return var;
}
public void setVar(String var) {
this.var = var;
}
public String getItems() {
return items;
}
public void setItems(String items) {
this.items = items;
}
@Override
public void doTag() throws JspException, IOException {
Object value = this.getJspContext().getAttribute(items);
if (value!=null && value instanceof List) {
Iterator iter = ((List)value).iterator();
while (iter.hasNext()) {
this.getJspContext().setAttribute(var, iter.next());
this.getJspBody().invoke(null);//响应页面
}
}
}
}
lang.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">
<tlib-version>1.0</tlib-version>
<short-name>pleaseTag</short-name>
<tag>
<name>iterate2 </name>
<tag-class>
com.lang.tag.IterateSimpleTag
</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>var</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>items</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
运行结果: