java - 使用 thymeleaf 同时迭代两个列表

标签 java list spring-boot iterator thymeleaf

<div class="form-group">
    <label class="control-label col-md-3 col-sm-3 col-xs-12">Roles
        <span class="required">*</span>
    </label>
    <thbody>
        <td><th:block th:each="myRoles : ${MyRoles}">
            <input type="checkbox" name="roles"
                th:value="${myRoles .id}" checked />
            <label th:text="${myRoles .roleName}"></label>
        </th:block>--</td>
    </thbody>

Current it is showing me only one list(present roles), I want to show all roles which are bind in object ${AllRoles} and checked only those roles which are currently given to a particular user.

我正在尝试将角色保存在我的 Controller 中:

Set<UserRole> myRolesSet;
myRolesSet= myusr.getRoles();

这是我在 View 中尝试执行的操作:

<thbody >
        <td><th:block th:each="allRoles : ${allrole}">
        <input  type="checkbox" name="roles" th:value="${allRoles.id}"
        th:checked="${#sets.contains(myRolesSet,allRoles.id)}? 'checked' " />
        <label th:text="${allRoles.roleName}"></label>
        </th:block></td>
</thbody>

最佳答案

您应该像下面的代码示例一样执行此操作:

首先,您需要将选定的角色放入 Controller 方法的 map 中,如下所示:

HashMap<Integer, Role> myRolesMap = new HashMap<Integer, Role>();

在本例中,我假设您使用整数键作为 HashMap 。

其次,您必须迭代 AllRoles 列表并确定用户是否具有当前迭代的角色,然后您应该选中该复选框。

    <thbody>
        <td><th:block th:each="role: ${AllRoles}">
            <input type="checkbox" name="roles"
                th:value="${role.id}" th:checked="${#maps.containsKey(myRolesMap, role.id)}" />
            <label th:text="${role.roleName}"></label>
        </th:block>--</td>
    </thbody>

关于java - 使用 thymeleaf 同时迭代两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54435381/

相关文章:

string - 如何在 haskell 中正确定义空字符串?

java - spring 处理存储库方法的方法

spring - 在用@Async 注释的方法中调用@Retryable 方法不起作用

java - 将 Maven 项目转换为多模块项目的子模块?

java - 制作小程序

java - Xpose中如何从变量中获取字符串?

java - 如何根据 Activity 配置文件访问 application-{profile}.properties 文件

java - 有人可以解释一下这段代码中发生了什么吗?无法理解简单的oops程序

java - AbstractList.add() 不支持的操作

android - 为什么在另一个 ArrayList<obj> 中添加 ArrayList<object> 会替换先前位置的内部 ArrayList<obj> 的值