Check mark on tables (JSTL)

252 Views Asked by At

I have the following class:

public class User {
    private String username;
    private String password;
    private List<Integer> roles;
    // Getters and Setters
}

I have a JSP that views all of the users currently registered. So I want it to be a summary of their username and the roles that they possess. Roles is the list that contains an index of the pages they can view.

Example:

+------------+--------+--------+--------+
| Username   | Page 1 | Page 2 | Page 3 |
+------------+--------+--------+--------+
| user1      |   ✔                 ✔   |
+------------+--------+--------+--------+
| user2      |            ✔        ✔   |
+------------+--------+--------+--------+
| user3      |   ✔                 ✔   |
+------------+--------+--------+--------+

Right now this is what I have:

<table cellpadding= "5">
    <tr>
        <th>Username</th>
        <th>Page 1</th>
        <th>Page 2</th>
        <th>Page 3</th>
    </tr>
  <c:forEach items="${users}" var="user">
    <tr align="left">
        <td>
            <c:out value="${user.username}"/>
        </td>
        /*insert conditional here*/
    </tr>
  </c:forEach>
</table>
1

There are 1 best solutions below

0
On

Since there is no built-in support in JSTL for list.contains(), you must fallback to an hack like looping the whole list every time, checking for the presence of the currently desired value:

  <c:forEach items="${users}" var="user">
    <tr align="left">
        <td>
            <c:out value="${user.username}"/>
        </td>

        <td>
            <c:forEach var="role" items="${user.roles}">
                <c:if test="${role eq 1}"> ✔ </c:if>
            </c:forEach>
        </td>
        <td>
            <c:forEach var="role" items="${user.roles}">
                <c:if test="${role eq 2}"> ✔ </c:if>
            </c:forEach>
        </td>
        <td>
            <c:forEach var="role" items="${user.roles}">
                <c:if test="${role eq 3}"> ✔ </c:if>
            </c:forEach>
        </td>
    </tr>
  </c:forEach>

That is quite sad for JSTL; I'm used to OGNL (used by Struts2) and it would be simply:

<s:if test="1 in user.roles"> ✔ </s:if>

That said, be aware that you should never carry a password like that (nor carry it at all).