【问题标题】:JSTL to iterate mapJSTL 迭代地图
【发布时间】:2013-01-07 01:23:53
【问题描述】:

我正在使用 JSTL 从 bean 类中获取值。 从 bean 类获得的值将是 java.util.Map 。通过以下代码成功获取值:

<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 列。

同样,如果key是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,这让生活变得轻松。

请给我一些建议以进一步进行。任何帮助都将是可观的。

【问题讨论】:

    标签: html map jstl iteration custom-tags


    【解决方案1】:

    在控制器中使用 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-19
      • 2011-07-06
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多