foreach标签的流程:
①、编写助手类
public class ForeachTag extends BodyTagSupport {
//存放数据源
private List<?> items;
//每次循环获取的对象放入pageContext中,并以var属性的值为key进行保存
//示例: 页面上标签var属性指定为item,则每次循环取出的对象(obj)将执行如下:
//pageContext.setAttribute(“item”, obj);
//页面中可以使用EL表达式取出对象中的属性, 如: ${item.name}
private String var;
public List<?> getItems() {
return items;
}
public void setItems(List<?> items) {
this.items = items;
}
public String getVar() {
return var;
}
public void setVar(String var) {
this.var = var;
}
@Override
public int doStartTag() {
if(Objects.isNull(this.items) || this.items.size() == 0) {
return SKIP_BODY;
}
Iterator<?> iterator = this.items.iterator();
Object obj = iterator.next();
this.pageContext.setAttribute(var, obj);
this.pageContext.setAttribute(“iterator”, iterator);
return EVAL_BODY_INCLUDE;
}
@Override
public int doAfterBody() {
Iterator<?> it = (Iterator<?>)this.pageContext.getAttribute(“iterator”);
if(it.hasNext()) {
this.pageContext.setAttribute(var, it.next());
return EVAL_BODY_AGAIN;
}
return SKIP_BODY;
}
}
②、测试数据辅助类
public class TestData {
public static List<Book> getBooks() {
List<Book> books = new ArrayList<>();
Book b1 = new Book();
b1.setId(1);
b1.setName(“水浒传”);
Book b2 = new Book();
b2.setId(2);
b2.setName(“红楼梦”);
Book b3 = new Book();
b3.setId(3);
b3.setName(“西游记”);
books.add(b1);
books.add(b2);
books.add(b3);
return books;
}
③、 在页面上使用标签
<%@page import=”com.zking.mvc.test.*,java.util.List” %>
<%@ page language=”java” contentType=”text/html; charset=utf-8″
pageEncoding=”utf-8″%>
<%@taglib prefix=”z” uri=”/zking” %>
<!DOCTYPE html”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
<title>Insert title here</title>
</head>
<body>
<h1><%=System.currentTimeMillis()%></h1>
<z:hello/>
<!– out –>
<z:out val=”adb”/>
<%
request.setAttribute(“name”, null);
%>
<z:out val=”${name}” defaultVal=”test”/>
<p>
<!– if –>
<z:if test=”${100 == 100}”>
测试if(100 == 100)
</z:if>
<z:if test=”${100 == 1}”>
测试if(100 == 1)
</z:if>
<p>
<!– foreach –>
<%
//获取测试数据
List<Book> books = TestData.getBooks();
//放入request对象中
request.setAttribute(“books”, books);
%>
<z:foreach items=”${books}” var=”book”>
<p>${book.id } – ${book.name }</p>
</z:foreach>
</body>
</html>