示例所示的源代码和本指南中未来的章节都可以在此找到Good Thymes Virtual Grocery GitHub repository.
一个购物网站
为了更好地解释Thymeleaf参与处理模板的概念,本教程将使用一个演示的应用程序,您可以从上面地址下载项目。
这个应用程序是一个虚构的虚拟商店网站,并将为我们提供足够的场景举例说明不同Thymeleaf特性。
我们需要为我们的应用程序设计一套非常简单的实体模型: Products(商品) 通过创建orders(订单)卖给Customers(客户)。我们也管理这些产品的Comments(评论)。应用程序模型如下:
我们的小应用程序也将有一个非常简单的服务层,服务对象包含方法如下:
public class ProductService {
...
public List<Product> findAll() {
return ProductRepository.getInstance().findAll();
}
public Product findById(Integer id) {
return ProductRepository.getInstance().findById(id);
}
}
最后,在web层有一个过滤器,将根据请求URL委托执行Thymeleaf-enabled命令:
private boolean process(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
try {
/*
* Query controller/URL mapping and obtain the controller
* that will process the request. If no controller is available,
* return false and let other filters/servlets process the request.
*/
IGTVGController controller = GTVGApplication.resolveControllerForRequest(request);
if (controller == null) {
return false;
}
/*
* Obt