springboot+thymeleaf实现自动生产静态页面方法(发布文章功能可用)
- 后台部分(网上copy来的,具体出处忘记了)
public static String createThymeleaf(String path, NewsArticle news){
try{
String filename = RandomUtil.RandomImgName();
filename = filename+".html";
//创建模版加载器
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setPrefix("templates/"); //模板文件的所在目录
resolver.setSuffix(".html"); //模板文件后缀
resolver.setCharacterEncoding("UTF-8");
//创建模板引擎
TemplateEngine templateEngine = new TemplateEngine();
//将加载器放入模板引擎
templateEngine.setTemplateResolver(resolver);
//创建字符输出流并且自定义输出文件的位置和文件名
FileWriter writer = new FileWriter(path+filename);
//创建Context对象(存放Model)
Context context = new Context();
//放入数据
context.setVariable("news",news);
//创建静态文件,"articleExample"是模板html名字
templateEngine.process("articleExample",context,writer);
return filename;
}catch (IOException e){
looger.error("自动生成页面出现异常:"+e.getMessage());
return "";
}catch (Exception e){
looger.error("自动生成页面出现异常:"+e.getMessage());
return "";
}
}
- 前台页面部分
<div class="container" style="background-color: #fff">
<div class="col-lg-1"></div>
<div class="col-lg-10" style="background-color: #FFFFFF; padding: 0px;">
<div class="col-lg-2"></div>
<div class="col-lg-8" style="text-align: center;">
<h4 class="newstitle" id="nTitle" th:text="${news.articletitle}"></h4>
<span style="font-size: 16px;" id="nTime" th:text="${#dates.format(news.createtime,'yyyy-MM-dd')}"></span>
</div>
<div class="col-lg-2"></div>
<div class="col-lg-12" style="border-bottom: solid 1px silver;"></div>
<div class="col-lg-12" id="newscontext"></div>
</div>
<div class="col-lg-1"></div>
</div>
<script>
$(document).ready(function () {
var id = $("#newsid").val();
$.get("/article/"+id,function (data) {
$("#newscontext").append(data.articlecontext);
$("#nTitle").text(data.articletitle)
$("#nTime").text(data.createtime);
})
})
</script>
(主要代码)亲测可用!!!