尝试从数据库中获取名称以显示在网页上但获取空白页面。让我知道我做错了什么,app确实有用,所以没有值得发布的堆栈跟踪
简单的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";
}
}
DAO:
@Repository
@Transactional
public interface CustomerDAO extends CrudRepository<Customer, String> {
public List<Customer> findAll();
}
默认地将Impl:
@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;
}
}
答案 0 :(得分:0)
您的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>
这将在您的每个toString()
对象上调用customer
方法。
如果您仍然看到一个空列表,您可以在查询调用中添加断点并运行调试器,或者只记录count / elements以查看您的存储库/数据库返回的内容。