【问题标题】:Cannot iterate over List in Thymeleaf [closed]无法遍历 Thymeleaf 中的列表 [关闭]
【发布时间】:2020-10-12 17:34:00
【问题描述】:

尝试在控制器中显示列表中的对象时出现错误。我正在使用 Spring Boot 框架。

这是错误:

org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'description' cannot be found on null

我使用的是 Spring Boot 2.3.4。下面是 maven pom.xml 文件中的依赖:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
</parent>

这是我的 thymeleaf html 视图:

<tbody>
    <tr th:each="proj : ${projectList}">
        <td th:text="${proj.name}"/>
        <td th:text="${proj.stage}"/>
        <td th:text="${project.description}"/>
    </tr>
</tbody>

我的项目@Entity 工作正常:

@Entity
public class Project {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int projectID;
    private String name;
    private String stage; //incomplete, not started, in progress
    private String description;
    ...
}

这是获取我的项目数据并尝试将其添加到模型的控制器。


@Controller
public class HomeController {

    @Autowired
    iProjectRepo projRepo;

    @GetMapping("/")
    public String showHome(Model model) {
        List<Project> projects = projRepo.findAll();
        model.addAttribute("projectList",projects);
        return "home";
    }
}

findAll() 返回一个 List 而不是 Iterable,因为我在 ProjectRepository 中更改了它,扩展了 CrudRepository

@Repository
public interface iProjectRepo extends CrudRepository<Project,Integer> {

    @Override
    List<Project> findAll();  //the findAll() by default returns an Iterable.  we override it and change the return type to be a list.
}

最后,这是我的项目结构:

【问题讨论】:

    标签: java spring spring-boot thymeleaf


    【解决方案1】:

    改变

    th:text="${project.description}"/>
    

    th:text="${proj.description}"/>
    

    【讨论】:

    • 那不就是别的吗!这就是问题所在。哈哈。这么愚蠢的错误,花了这么多时间!
    • 非常感谢@Alien!
    • 不客气...请将答案标记为已接受的解决方案。
    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2019-12-24
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多