Thymeleaf:在模板中打印集

时间:2018-08-26 11:36:56

标签: spring-boot thymeleaf

我有一个基本的SpringBoot 2.0.4.RELEASE应用程序。使用Spring Initializer,JPA,嵌入式Tomcat,Thymeleaf模板引擎并将其打包为可执行JAR文件。

我有这个实体:

@Entity
@Table(name="t_user")
public class User implements Serializable, UserDetails {

 @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JsonIgnore
    private Set<UserRole> userRoles = new HashSet<>();

public Set<UserRole> getUserRoles() {
        return userRoles;
    }

    public void setUserRoles(Set<UserRole> userRoles) {
        this.userRoles = userRoles;
    }
}

这:

@Entity
@Table(name = "t_user_role")
public class UserRole implements Serializable {

    /** The Serial Version UID for Serializable classes. */
    private static final long serialVersionUID = 1L;

    public UserRole() {

    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    public UserRole(User user, Role role) {
        this.user = user;
        this.role = role;
    }


    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "user_id")
    private User user;


    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "role_id")
    private Role role;
...
}

,并希望显示用户的所有角色,所以我使用以下代码:

 <td class="col_name"   th:text="${user.userRoles.role}"></td><!-- ROLES -->

但是我在浏览器中看到的实际上是这样:

com.tdk.backend.persistence.domain.backend.User.userRoles

1 个答案:

答案 0 :(得分:0)

您将要遍历对象集以打印role值。您可以使用Thymeleaf的th:each语法:

<td class="col_name">
    <span th:each="userRole : ${user.userRoles}" th:text="${userRole.role}">[role]</span><!-- format with line breaks as needed -->
</td>

您也可以查看lists实用程序并调用toString()以快速而肮脏的方式输出:

<td class="col_name">
    <span th:text="${#lists.toString(user.userRole.role)}">[role]</span>
</td>

您可以选择使用<span>删除th:remove="tag"标签。