本文共 2406 字,大约阅读时间需要 8 分钟。
在商城项目中,通过技术手段实现静态页面生成,可以有效提升网站性能和用户体验。本文将介绍如何利用Freemarker模板引擎和消息队列技术,实现商品上架后的静态页面生成机制。
原有的产品详情页面通常是JSP形式,改写为静态HTML模板后,需要注意以下几点:
<#list persons as person>实现。<#include>标签引入公共模块,例如导入 footer.html。<meta charset="UTF-8">,确保页面字符集一致。在项目中添加必要的Freemarker配置文件freemarker.xml:
为了实现动态静态页面生成,需要设置消息队列监听:
public class CustomMessageListener implements MessageListener { @Autowired private StaticPageService staticPageService; @Override public void onMessage(Message message) { try { String productId = ((ActiveMQTextMessage) message).getText(); // 查询商品详情 Product product = cmsService.selectProductById(productId); // 查询库存信息 List skus = cmsService.selectSkuListByProductId(productId); Set colors = new HashSet<>(); for (Sku sku : skus) { colors.add(sku.getColor()); } Map root = new HashMap<>(); root.put("product", product); root.put("skus", skus); root.put("colors", colors); staticPageService.productStaticPage(root, productId); } catch (JMSException e) { e.printStackTrace(); } }} 静态页面生成的具体实现逻辑:
public void productStaticPage(Maproot, String id) { String path = getPath("/html/product/" + id + ".html"); File f = new File(path); File parentFile = f.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } try { Template template = conf.getTemplate("productDetail.html"); Writer out = new OutputStreamWriter(new FileOutputStream(f), "UTF-8"); template.process(root, out); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != out) { out.close(); } } catch (IOException e) { e.printStackTrace(); } }}
在产品列表页面,修改商品链接:
...
完成上述配置后,通过浏览器访问商城页面,验证静态页面生成效果。
通过以上步骤,可以实现商品上架后自动生成静态HTML页面,提升网站性能表现。
转载地址:http://qnse.baihongyu.com/