|
| 1 | +package cn.tellsea.service.impl; |
| 2 | + |
| 3 | +import cn.tellsea.service.ThymeleafService; |
| 4 | +import lombok.extern.slf4j.Slf4j; |
| 5 | +import org.springframework.beans.factory.annotation.Autowired; |
| 6 | +import org.springframework.stereotype.Service; |
| 7 | +import org.thymeleaf.TemplateEngine; |
| 8 | +import org.thymeleaf.context.Context; |
| 9 | + |
| 10 | +import java.io.File; |
| 11 | +import java.io.PrintWriter; |
| 12 | +import java.util.HashMap; |
| 13 | +import java.util.Map; |
| 14 | + |
| 15 | +@Slf4j |
| 16 | +@Service |
| 17 | +public class ThymeleafServiceImpl implements ThymeleafService { |
| 18 | + |
| 19 | + public static final String destPath = "D:/temp/static"; |
| 20 | + |
| 21 | + @Autowired |
| 22 | + private TemplateEngine templateEngine; |
| 23 | + |
| 24 | + public Map<String, Object> loadModel(Long id) { |
| 25 | + // 讲道理,这里加载的数据是根据id从数据库查询出来的,我这里就写固定了 |
| 26 | + Map<String, Object> map = new HashMap<>(); |
| 27 | + map.put("name", "tellsea"); |
| 28 | + map.put("age", 20); |
| 29 | + map.put("email", "3210054449@qq.com"); |
| 30 | + return map; |
| 31 | + } |
| 32 | + |
| 33 | +/** |
| 34 | + * 创建html页面 |
| 35 | + * |
| 36 | + * @param spuId |
| 37 | + * @throws Exception |
| 38 | + */ |
| 39 | +public void createHtml(Long spuId) { |
| 40 | + // 上下文 |
| 41 | + Context context = new Context(); |
| 42 | + context.setVariables(loadModel(spuId)); |
| 43 | + // 输出流 |
| 44 | + File dest = new File(destPath, spuId + ".html"); |
| 45 | + if (dest.exists()) { |
| 46 | + dest.delete(); |
| 47 | + } |
| 48 | + try (PrintWriter writer = new PrintWriter(dest, "UTF-8")) { |
| 49 | + // 生成html |
| 50 | + templateEngine.process("id", context, writer); |
| 51 | + } catch (Exception e) { |
| 52 | + log.error("[静态页服务]:生成静态页异常", e); |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | + public void deleteHtml(Long id) { |
| 57 | + // 输出流 |
| 58 | + File dest = new File(destPath, id + ".html"); |
| 59 | + if (dest.exists()) { |
| 60 | + dest.delete(); |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments