【问题标题】:Spring Boot and Thymeleaf: field 'name' cannot be found on nullSpring Boot 和 Thymeleaf:在 null 上找不到字段“名称”
【发布时间】: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

你能建议我如何解决这个问题吗?

【问题讨论】:

    标签: spring-mvc spring-boot


    【解决方案1】:

    此处输入错误

    th:each="Persons : ${persons} 更改为th:each="person : ${persons}

    【讨论】:

    • 天啊。抱歉,我以为第一个字符串“Person”只是要在页面中打印的文本,对框架没有影响。抱歉,从您的背景中删除 JSF 需要时间 :-)
    【解决方案2】:

    th:each 中的变量 Persons 与迭代中的拼写不同。像这样更改您的代码:

     <tr th:each="person : ${persons}">
       <th>Name</th>
       <th>Surname</th>
        <td th:text="${person.name}" />
        <td th:text="${person.surname}" />
    </tr>
    

    【讨论】:

    • 感谢您也提供解决方案。
    • @Carla 当然。但提前 15 分钟回答!
    猜你喜欢
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 2016-04-11
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 2018-03-01
    相关资源
    最近更新 更多