【发布时间】:2018-12-03 08:03:17
【问题描述】:
我无法在我的模板页面中显示我在模型中拥有的对象的字段。我在 StackOverFlow 上检查过类似的问题,但它们都指向错误的命名(模型名称!= 使用的 EL 表达式)。我已经仔细检查了它,但仍然找不到问题的原因。
这是我的html:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot Thymeleaf Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<body>
<h2>Hello</h2>
<table>
<tr th:each="Persons:${persons}">
<th>Name</th>
<th>Surname</th>
<td th:text="${person.name}" />
<td th:text="${person.surname}" />
</tr>
</tbody>
</table>
</body>
</html>
这是我的控制器类:
@Controller
@RequestMapping("/persons")
public class PersonController {
private static List<Person> persons = new ArrayList();
static {
Person p = new Person("admin", "admin");
persons.add(p);
}
@GetMapping
public String getAllPersons(Model model) {
model.addAttribute("persons",persons);
return "persons";
}
显然,有一个带有字段(和 getter/setter)的 Person 类:
public class Person {
private String name;
private String surname;
public Person(String name, String surname) {
super();
this.name = name;
this.surname = surname;
}
// getters/setters
}
请求“/persons”页面时显示如下错误:
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'name' cannot be found on null
你能建议我如何解决这个问题吗?
【问题讨论】: