需要的pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
代码:
package com.changgou.web.item.service.impl;
import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.CategoryFeign;
import com.changgou.goods.feign.GoodsFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.pojo.Category;
import com.changgou.pojo.Sku;
import com.changgou.pojo.Spu;
import com.changgou.web.item.service.ItemService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author :gzy
* @date :Created in 2019/8/25
* @description :
* @version: 1.0
*/
@Service
public class ItemServiceImpl implements ItemService {
//在application.yml有配置,存放静态页的地方
//pagepath: D:\GitJavaProgects\ChangGou\changgou_parent\changgou_web\changgou_web_item\src\main\resources\templates\items
@Value("${pagepath}")
private String pagePath;
@Autowired
private TemplateEngine templateEngine;
@Autowired
private SpuFeign spuFeign;
@Autowired
private CategoryFeign categoryFeign;
@Autowired
private GoodsFeign goodsFeign;
@Override
public void staticPage(String spuid) {
Map map = new HashMap<>();
Spu spu = spuFeign.findSpuByid(spuid);
map.put("spu",spu);
//查分类
Category category1 = categoryFeign.findCategoryById(spu.getCategory1Id());
Category category2 = categoryFeign.findCategoryById(spu.getCategory2Id());
Category category3 = categoryFeign.findCategoryById(spu.getCategory3Id());
map.put("category1",category1);
map.put("category2",category2);
map.put("category3",category3);
//查照片
String images = spu.getImages();
if(!StringUtils.isEmpty(images)){
String[] img = images.split(",");
map.put("imageList",img);
}
//查库存
List<Sku> skuList = goodsFeign.findBySpuId(spuid);
map.put("skuList",skuList);
//查规格
String specItems = spu.getSpecItems();
//不指定map类型,它自动转为string,list
Map specmap = JSON.parseObject(specItems, Map.class);
map.put("specificationList",specmap);
Context context = new Context();
context.setVariables(map);
//流
File file = new File(pagePath);
if(!file.exists()){
file.mkdirs();
}
Writer writer = null;
try {
writer = new PrintWriter(pagePath + "/" + spuid + ".html","utf-8");//乱码
//Thymeleaf生成静态页
templateEngine.process("item",context,writer);
} catch (Exception e) {
e.printStackTrace();
}
finally {
if(writer!=null){
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}