问题描述 :
jsp 的pageContext域中存在User对象的users列表,想在jsp文件中遍历users. 或者Set、Map、及数组
<%
class User{
private String name;
private String email;
public User(String name,String email){
this.name=name;
this.email=email;
}
}
List<User> users=new ArrayList<>();
users.add(new User("user1","123@qq.com"));
users.add(new User("user2","1234@qq.com"));
users.add(new User("user3","12345@qq.com"));
users.add(new User("user1","123456@qq.com"));
users.add(new User("user5","1234567@qq.com"));
pageContext.setAttribute("users",users);
%>
遍历方式
<ct:forEach items="${users}" , var="user">
${user.name}---${user.email}<br/>
</ct:forEach>
WEB页面输出
user1---123@qq.com
user2---1234@qq.com
user3---12345@qq.com
user4---123456@qq.com
user5---1234567@qq.com
1、实现类 ForEach.java
package app.tag;
package app.tag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.*;
public class ForEachList extends SimpleTagSupport {
private Object items;
private String var;
public void setItems(List items) {
this.items = items;
}
public void setVar(String var) {
this.var = var;
}
public Collection getColl(){
if(items instanceof List)
return (List)items;
else if(items instanceof Set)
return (Set)items;
else if(items instanceof Map)
return ((Map)items).entrySet();
else if(items.getClass().isArray()){
List coll=new ArrayList();
for(int i=0;i< Array.getLength(items);i++){
coll.add(Array.get(items,i));
}
return coll;
}
return null;
}
@Override
public void doTag() throws JspException, IOException{
for (Object obj:
getColl()) {
this.getJspContext().setAttribute(var,obj); //将obj保存在pageScope中,以便EL表示式读取数据
this.getJspBody().invoke(null);//将标签体写入输出流
}
}
}
2、注册标签 ct.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<tlib-version>1.0</tlib-version>
<short-name>ct</short-name>
<uri>http://www.cooooode.com/taglib</uri>
<tag>
<name>forEach</name>
<tag-class>app.tag.ForEach</tag-class>
<body-content>scriptless</body-content><!--可以使用EL-->
<attribute>
<name>items</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue><!--可以使用EL,JSP表达式-->
</attribute>
<attribute>
<name>var</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>
3、tablib指令
<%@ taglib uri="http://www.cooooode.com/taglib" prefix="ct"%>