有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何访问thymeleaf中对象属性的属性?

假设我想访问一个名为post的对象。Post有一个名为Category类型的Category的实例变量

在Java控制器类中

model.addAttribute("posts", postRepository.findPostsByUser(user));

在thymeleaf html文件中

<tr data-th-each="post : ${posts}">

我想知道是否有可能访问下面的

{post.category.name}

为了澄清,我在下面介绍了java类。每个实例都有关联的setter和getter

@Entity
public class Post {

@ManyToOne
@JoinColumn(name = "category_id")
private Category category;


@Entity
public class Category {

private String name;

共 (2) 个答案

  1. # 1 楼答案

    我认为你需要更改你的实体代码

    @Entity
    public class Post {
    
       private Category category;
    
       @ManyToOne(cascade = CascadeType.ALL)
       @JoinColumn(name = "category_id", nullable = false)
       public Category getCategory () {
         return this.category;
       }
    
       public void setCategory (Category category ) {
         this.category = category ;
       }
    
    }
    

    您需要按照以下步骤实现thymeleaf html页面

    <tr th:each="post : ${posts}">
       <td> <span th:utext="{post.category.name}" /></td>
    </tr>
    

    希望对你有所帮助

  2. # 2 楼答案

    你必须提出一个条件:

    <tr th:each="post:${posts}">
        <td th:text="${post.category}!=null? ${post.category.name}:''"></td>
    </tr>
    

    :)