2012-03-02 84 views
0

HelloTag.Javaswitch語句/迭代中JSTL

public class HelloTag extends SimpleTagSupport { 

@Override 
public void doTag() throws JspException, IOException { 
    JspWriter out = getJspContext().getOut(); 

    ArrayList outerList = new ArrayList(); 
    ArrayList innerList = null; 
    for (int i = 0; i < 5; i++) { 
     innerList = new ArrayList(); 
     innerList.add("1"); 
     innerList.add("Name"); 
     outerList.add(innerList); 
    } 
    for (int i = 0; i < outerList.size(); i++) { 
     for (int j = 0; j < innerList.size(); j++) { 
      out.println(innerList.get(j)); 
     } 
    } 
} 
} 

在JSP文件, 還有就是下面的代碼片段:

<body> 
    <ct:Hello></ct:Hello> 
</body> 

當我運行JSP文件,該文件顯示準確的結果;但

我要採取一切價值都是來自於自定義標籤類的決定

<c:set var="name" scope="" value=""/> 
<c:choose> 
<c:when test="${name == 1}"> 
    This is Your ID:- 
</c:when> 
<c:otherwise> 
    This is Your Name 
</c:otherwise> 
</c:choose> 

上面的代碼是隻是舉例的緣故。請更新我如何對來自自定義標記類的每個值做出決定。

解釋我的問題另一種方法是,我要存儲在一個變量的每一個值,然後取一個大約只使用JSTL不Scriplet標籤着眼於上述方案(HelloTag.Java

該值決定
+0

據我所知,SimpleTagSupport不允許你有JSP主體內容,如果要實現類似,那麼你需要使用BodyTagSupport – Dapeng 2012-03-02 09:26:49

+0

親愛@Dapeng東西,我將通過一個例子來解決問題 – 2012-03-02 14:40:22

回答

2

真的不清楚你在問什麼。但是,你的標籤就是這樣,只是循環遍歷每個外部列表的內部列表(實際上,我猜它應該這樣做,但它有一個錯誤,所以它不會)。

由於JSTL <c:forEach>標籤已經做到了,所以您不需要自定義標籤就可以做到這一點。假設你有存儲的請求outerList(或網頁,或會話,或應用程序)屬性:

<%-- iterate through the outer list --%> 
<c:forEach var="innerList" items="${outerList}"> 
    <%-- iterate through the innerList --%> 
    <c:forEach var="element" items="${innerList}"> 
     <%-- do what you want with the element --%> 
    </c:forEach> 
</c:forEach> 

從你的問題,在我看來,你不應該有一個內部列表,雖然。相反,外部列表應該包含對象(例如Person類的實例),它們具有getId()getName()方法。因此,循環是:

<%-- iterate through the outer list --%> 
<c:forEach var="person" items="${personList}"> 
    ID : ${person.id}<br/> 
    Name : <c:out value="${person.name}"/> 
</c:forEach>