带有 MySQL 名称的 Thymeleaf 循环
Posted
技术标签:
【中文标题】带有 MySQL 名称的 Thymeleaf 循环【英文标题】:Thymeleaf loop with names from MySQL 【发布时间】:2017-09-12 05:57:01 【问题描述】:试图从数据库中获取名称以显示在网页上,但得到一个空白页面。让我知道我做错了什么,应用确实可以工作,所以没有值得发布的堆栈跟踪
简单的 Thymeleaf 视图:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:text="http://www.w3.org/1999/xhtml">
<head lang="en"></head>
<body th:each="customer: $customers">
<h2 th:text="$customer"></h2>
</body>
</html>
控制器:
@Controller
public class CustomerController
@Autowired
private CustomerDAO customerDAO;
@RequestMapping("/list")
public String listCustomers(Model model)
List<Customer> customers = customerDAO.findAll();
model.addAttribute("customers", customers);
return "list-customers";
道:
@Repository
@Transactional
public interface CustomerDAO extends CrudRepository<Customer, String>
public List<Customer> findAll();
实施:
@Transactional
@Repository
public abstract class CustomerDAOImpl implements CustomerDAO
private SessionFactory sessionFactory;
private CustomerDAO customerDAO;
@Override
public List<Customer> findAll()
return customerDAO.findAll();
实体:
@Entity
@Table(name = "customer")
public class Customer implements Serializable
@Column(name = "id")
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
public Customer()
public Customer(String firstName, String lastName, String company)
this.firstName = firstName;
this.lastName = lastName;
this.email = company;
@Override
public String toString()
return "Customer" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
'';
public int getId()
return id;
public void setId(int id)
this.id = id;
public String getFirstName()
return firstName;
public void setFirstName(String firstName)
this.firstName = firstName;
public String getLastName()
return lastName;
public void setLastName(String lastName)
this.lastName = lastName;
public String getCompany()
return email;
public void setCompany(String company)
this.email = company;
【问题讨论】:
使用<body th:each="customer: $customers">
您可以在一个 HTML 中创建多个正文标签。这在 HTML 中是不允许的。保持身体标签清洁并使用例如一个额外的 div 标签。
【参考方案1】:
您的 HTML 应更新为:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:text="http://www.w3.org/1999/xhtml">
<head lang="en"></head>
<body>
<div th:each="customer: $customers">
<h2 th:text="$customer"></h2>
</div>
</body>
</html>
这将对您的每个 customer
对象调用 toString()
方法。
如果您仍然看到一个空列表,您可以在查询调用中添加断点并运行调试器,或者简单地记录计数/元素以查看您的存储库/数据库返回的内容。
【讨论】:
以上是关于带有 MySQL 名称的 Thymeleaf 循环的主要内容,如果未能解决你的问题,请参考以下文章
spring boo的简单搭建(eclipse+springboot + redis + mysql + thymeleaf)
SpringBoot + MyBatis-Plus +MySQL8 +Thymeleaf +LayUI通用业务模块增删改查