步骤
①编写助手类
②编写标签库描述标签(tld)
③在页面上引入标签使用
1、foreach标签
编写助手类
我们先设置属性这里我们需要了解在foreach中有两个值分别为与要遍历的集合和它对应的键
package com.zking.je09.tagdemo.tag;
import java.util.Iterator;
import java.util.List;
import javax.servlet.jsp.tagext.BodyTagSupport;
public class ForeachTag extends BodyTagSupport{
//存放数据眼 ?相当于object
private List<?> items;
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(this.items ==null || 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");
//在这里为什么不用while而是用if
if(it.hasNext()) {
//可以用this.var也可以用var
this.pageContext.setAttribute(this.var, it.next());
return EVAL_BODY_AGAIN;
}
return SKIP_BODY;
}
}
2、编写tld文件
首先我们要设置标签
<tag>
<name>foreach</name>
<tag-class>com.zking.mvc.tag.IfTag</tag-class>
<!--该标签有标签体-->
<body-content>jsp</body-content>
<attribute>
<name>itmes</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>var</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
然后我们把测试用的对象和给对象增加测试数据的类和方法写好
package com,zking.tagdemo.tag;
public class Book {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
添加测试数据的方法
package com.zking.tagdemo.tag;
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;
}
}
3、最后在jsp中进行测试
注意:一定要引用写好的辅类和添加数据类和方法
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!-- 引入标签库 -->
<%@taglib prefix="z" uri="/zking" %><!-- z表示引用jsp标签前缀 -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<!-- 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>