【问题标题】:Thymeleaf does not see reference from ControllerThymeleaf 没有看到来自控制器的参考
【发布时间】:2017-05-26 11:48:31
【问题描述】:

我正在尝试使用 Thymeleaf 在 html 页面上显示本地数据库 (PostgreSQL) 中的所有客户。我的项目正在使用 Spring Boot。

连接和从数据库获取数据不是这个问题的重点(或者是吗?)。关键是百里香没有看到我通过控制器的模型。

homePage.html

!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:th="http://www.thymeleaf.org">

<head>
<title>Opera</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Opera home page'" />

<ul th:each="customer : ${customers}">
<li>
    <span th:text="${customers.getFirstName}">Name</span>
    <span th:text="${customers.getLastName}">Surname</span>
    <span th:text="${customers.getPhone}">Phone</span>
    <span th:text="${customers.getEmail}">e-mail</span>
</li>
</ul>
</body>
</html>

HomePageController.java

@Controller
@RequestMapping("/")
public class HomePageController {

    private CustomerRepository customerRepository;

    @Autowired
    public HomePageController(CustomerRepository customerRepository){
        this.customerRepository = customerRepository;
    }


    @RequestMapping(method = RequestMethod.GET)
    public String homePage(Model model) {
        List<Customer> customers = Lists.newArrayList(customerRepository.findAll());
        model.addAttribute("customers", customers);
        return "homePage";
    }
}

CustomerRepository.java

@Repository
public interface CustomerRepository extends CrudRepository<Customer, Long> {
}

客户.java

@Entity
@Getter @Setter
public class Customer {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;
    @NotNull private String firstName;
    @NotNull private String lastName;
    @NotNull private String phoneNumber;
    @NotNull private String email;

    protected Customer(){}

    public Customer(Long id, String firstName, String lastName, String phoneNumber, String email){
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.phoneNumber = phoneNumber;
        this.email = email;
    }

    @Override
    public String toString(){
        return String.format(
            "Customer[id=%d, firstName='%s', lastName='%s', phoneNumber='%s', emailr='%s']",this.getId(),
            firstName, lastName, phoneNumber, email);
    }
}

显示问题的 html 文件的屏幕截图: screen

编辑:一些英文更正:(

【问题讨论】:

    标签: java postgresql spring-boot spring-data thymeleaf


    【解决方案1】:

    不要在模板中使用 getter。这样做:

    <span th:text="${customer.firstName}">Name</span>
    

    抱歉,您还必须删除 s

    【讨论】:

    • 我将其更改为 customer.firstName 等,但 thymeleaf 似乎根本无法识别客户列表,因此 for each 循环甚至无法启动
    • Nvm,就是这样 :) 它的工作,但客户仍然突出。显然是它的 IntelliJ 错误。谢谢!
    猜你喜欢
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    相关资源
    最近更新 更多