一:引入freemarker坐标
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
二:spring配置文件中增加freemarker配置信息
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl/" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
三:使用freemarkerConfig生成静态页面
@Service
public class ItemPageServiceImpl implements ItemPageService {
@Value("${pagedir}")
private String pagedir;
@Autowired
private FreeMarkerConfig freeMarkerConfig;
@Autowired
private TbGoodsMapper goodsMapper;
@Autowired
private TbGoodsDescMapper goodsDescMapper;
@Autowired
private TbItemCatMapper itemCatMapper;
@Autowired
private TbItemMapper itemMapper;
@Override
public boolean genItemHtml(Long goodsId){
try {
Configuration configuration = freeMarkerConfig.getConfiguration();
Template template = configuration.getTemplate("item.ftl");
Map dataModel=new HashMap<>();
//1.加载商品表数据
TbGoods goods = goodsMapper.selectByPrimaryKey(goodsId);
dataModel.put("goods", goods);
//2.加载商品扩展表数据
TbGoodsDesc goodsDesc = goodsDescMapper.selectByPrimaryKey(goodsId);
dataModel.put("goodsDesc", goodsDesc);
//3.商品分类
String itemCat1 = itemCatMapper.selectByPrimaryKey(goods.getCategory1Id()).getName();
String itemCat2 = itemCatMapper.selectByPrimaryKey(goods.getCategory2Id()).getName();
String itemCat3 = itemCatMapper.selectByPrimaryKey(goods.getCategory3Id()).getName();
dataModel.put("itemCat1", itemCat1);
dataModel.put("itemCat2", itemCat2);
dataModel.put("itemCat3", itemCat3);
//4.SKU分类列表
TbItemExample example=new TbItemExample();
TbItemExample.Criteria criteria = example.createCriteria();
criteria.andStatusEqualTo("1");//状态为有效
criteria.andGoodsIdEqualTo(goodsId);//指定SPU ID
example.setOrderByClause("is_default desc");//按照状态降序,保证第一个为默认
List<TbItem> itemList = itemMapper.selectByExample(example);
dataModel.put("itemList", itemList);
Writer out=new FileWriter(pagedir+goodsId+".html");
template.process(dataModel, out);
out.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
四:item.ftl模板
<body ng-app="pyg" ng-controller="itemController" ng-init="num=1;loadSku()">
<!-- 头部栏位 -->
<#include "head.ftl">
<#--图片列表 -->
<#assign imageList=goodsDesc.itemImages?eval />
<#--规格列表 -->
<#assign specificationList=goodsDesc.specificationItems?eval />
<div class="py-container">
<div id="item">
<div class="crumb-wrap">
<ul class="sui-breadcrumb">
<li><a href="#">${itemCat1}</a></li>
<li><a href="#">${itemCat2}</a></li>
<li><a href="#">${itemCat3}</a></li>
</ul>
</div>
........