【发布时间】: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