2013-01-23 98 views
1

獲取bean類中的值。 從bean類獲得的值將是java.util.Map。在通過下面的代碼得到的值是成功:JSTL使用JSTL從迭代映射

<c:forEach items="${bean.map}" var="item"> 
    <c:out value="${item.key}"/> = <c:out value="${item.value}"/><br/> 
</c:forEach> 

獲得鍵值對後,我需要創建一個表4行7列。 地圖:

map.put(2, true); 
map.put(18, true); 

在地圖的關鍵是從1-28的和值將是TRUE或FALSE。

如果鍵值爲2且值爲TRUE,則在表格的(1,2)中放置複選標記,例如:第1行第2列。同樣,如果鍵爲18,則需要在表格(3,4)中放置一個複選標記。

  <table border="1" width="100%"> 
     <tr> 
     <th>1</th> 
     <th>2</th> 
     <th>3</th> 
     <th>4</th> 
     <th>5</th> 
     <th>6</th> 
     <th>7</th> 
     </tr> 
     <c:forEach items="${bean.map}" var="item" > 
     <tr> 
     <td><c:out value="${item.value}"/></td> 
     </tr> 
     </c:forEach> 
     </table> 

我不知道如何繼續下去,因爲我只限於使用JSTL,並且是JSTL的新手。我不允許使用javascript或jquery,這使得生活變得輕鬆。

請給我一些建議繼續下去。任何幫助將是可觀的。

回答

0

在控制器中使用Java代碼將條目拆分爲行,而不是在視圖中使用JSTL進行拆分。這是可能的,但通過在Java中執行它,一切都會更容易。

而使用地圖來包含鍵從1到28是有點奇怪。爲什麼不使用28布爾列表?

/** 
* Returns a list of 4 lists of booleans (assuming the map contains 28 entries going 
* from 1 to 28). Each of the 4 lists contaisn 7 booleans. 
*/ 
public List<List<Boolean>> partition(Map<Integer, Boolean> map) { 
    List<List<Boolean>> result = new ArrayList<List<Boolean>>(4); 
    List<Boolean> currentList = null; 
    for (int i = 1; i <= 28; i++) { 
     if ((i - 1) % 7 == 0) { 
      currentList = new ArrayList<Boolean>(7); 
      result.add(currentList); 
     } 
     currentList.add(map.get(i)); 
    } 
    return result; 
} 

而在你的JSP:

<table border="1" width="100%"> 
    <tr> 
     <th>1</th> 
     <th>2</th> 
     <th>3</th> 
     <th>4</th> 
     <th>5</th> 
     <th>6</th> 
     <th>7</th> 
    </tr> 
    <c:forEach items="${rows}" var="row"> 
     <tr> 
      <c:forEach items="row" var="value">    
       <td><c:out value="${value}"/></td> 
      </c:forEach> 
     </tr> 
    </c:forEach> 
</table>