1. 程式人生 > >JSP自定義標籤遍歷List (ct:forEach)

JSP自定義標籤遍歷List (ct:forEach)

問題描述 : jsp 的pageContext域中存在User物件的users列表,想在jsp檔案中遍歷users.

<%
    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","
[email protected]
")); users.add(new User("user2","[email protected]")); users.add(new User("user3","[email protected]")); users.add(new User("user1","[email protected]")); users.add(new User("user5","[email protected]")); pageContext.setAttribute("users",users); %>

遍歷方式

<ct:forEach items="${users}" , var="user">
	${user.name}---${user.email}<br/>
</ct:forEach>

WEB頁面輸出

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

1、實現類 ForEachList.java

package app.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.util.List;

public class ForEachList extends SimpleTagSupport {
    private List items; //標籤屬性 List
    private String var; //標籤屬性 List中物件的名稱
    public void setItems(List items) {
        this.items = items;
    }
    public void setVar(String var) {
        this.var = var;
    }
    @Override
    public void doTag() throws JspException, IOException{
        for (Object obj:
             items) {
            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.ForEachList</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"%>