java - Thymeleaf 模板无法评估与模型相关的表达式

标签 java spring spring-boot model-view-controller thymeleaf

我正在开发我的第一个 Spring boot 应用程序。它使用 MVC 模式和 Thymleaf 来渲染 HTML。我有一个简单的 HTML 模板,它显示模型变量。不幸的是,我在访问该特定映射/url 时遇到以下错误:

There was an unexpected error (type=Internal Server Error, status=500). Exception evaluating SpringEL expression: "employee.Lastname" (template: "Employees" - line 22, col 8)

我无法弄清楚问题出在哪里。

我使用的是thymleaf 3.0.11,Spring boot 2.1.2

我检查了以下内容:

  1. 我正在点击预期的模板(我已经运行了包含静态内容的相同模板)
  2. 我还尝试显示除姓氏之外的其他变量,并且它正在工作
  3. NO 值为 null 或为空

我的员工模型类如下(没有 getter-setters):

public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long employeeId;
    private String name;
    private int salary;
    private String Lastname;

    @ManyToMany(cascade = { CascadeType.MERGE, CascadeType.REFRESH })
    @JoinTable(name = "Project_Employee", joinColumns = @JoinColumn(name = "employeeId"), inverseJoinColumns = @JoinColumn(name = "projectId"))
    private Set<Project> projects = new HashSet<Project>();

    public Employee() {
        super();
    }

我的 HTML 模板如下:

<!DOCTYPE html>
<html lang="en" xmlns:th= "http://www.thymeleaf.org">
<head>
     <meta charset= "UTF-8"/>
     <title>Employee View</title>
</head>


<body>
        <h1>WELCOME</h1>
<table>     
        <tr >

            <th>First Name        </th>
            <th>Last Name         </th> 
            <th>Salary            </th>
        </tr>

        <tr th:each = "employee: ${Employee}">
            <td th:text ="${employee.name}"></td> 
            <td th:text ="${employee.salary}"></td>
            <td th:text ="${employee.Lastname}"></td>

        </tr> 

</table>        
</body>
</html>

和 Controller ID 如下(只是特定方法):

@RequestMapping("/Employees")
    public String getEmployee(Model model)
    {

        model.addAttribute("Employee", employeeRepository.findAll());
        return "Employees";

    }

最佳答案

可能找不到您的 getter 方法,因为您的字段名称大写。

尝试在类中将其更改为 private String lastname;,在模板中将其更改为 ${employee.lastname}

来自第 8.8 节,推断名称的大写,在 JavaBeans Specification 中:

Java programmers are accustomed to having normal identifiers start with lower case letters. Vigorous reviewer input has convinced us that we should follow this same conventional rule for property and event names.

关于java - Thymeleaf 模板无法评估与模型相关的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57153495/

相关文章:

java - 请求处理失败;嵌套异常是 org.hibernate.MappingException : Unknown entity

java - 有没有一种方法可以在 Spring Boot 应用程序中自定义 JPA 实体的仅一个特定 String 类型字段的序列化?

gradle - Spring Boot Vaadin静态内容

java - 使用 javamail API 阅读邮件时出现阿拉伯语内容问题

java - 约束布局 : Add UI elements programmatically

java - 在 scala 应用程序中处理 swing 异常

java - Base64上传-性能

java - 如何创建 LIFO 队列 channel

spring-boot - 没有 WebSecurityConfigurerAdapter 和两个 AuthenticationProvider 的 Spring Security

Java:如何让线程等待用户的IO然后继续