SpringBoot集成Freemarker
- 主要特征:静态页面,无接口交互
- 数据实时性不高且体量小的网站可采用生成静态html的形式
- 数据提前渲染至html内,若发生数据更新,则重新渲染数据
- CDN加速让网站不再龟速
1. 引入Maven依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
2. 创建ftl
<html>
<head>
<title>啦啦啦啦啦</title>
</head>
<body>
<h1>侠客行</h1>
<p>${author!}</P>
<#if (poem?size)!=0>
<#list poem as item>
<p>${item.first!}${item.second!}</p></br>
</#list>
</#if>
</body>
</html>
3. 创建freeMarker工具类
@Slf4j
@Component
public class FreeMarkerUtil {
private static Configuration config;
private static String serverPath;
@Value("${spring.servlet.multipart.location:D:/static/}")
public void setServerPath(String serverPath) {
FreeMarkerUtil.serverPath = serverPath;
}
public static void createHtml(String templateName, String targetFileName, String ftlPath, String htmlPath, Map<String, Object> map) {
try{
//创建fm的配置
config = new Configuration();
//指定默认编码格式
config.setDefaultEncoding("UTF-8");
//设置模版文件的路径
config.setDirectoryForTemplateLoading(new File(serverPath+ftlPath));
//获得模版包
Template template = config.getTemplate(templateName);
//从参数文件中获取指定输出路径
String path = serverPath+htmlPath;
//生成的静态页存放路径如果不存在就创建
File file = null;
file=new File(path);
if (!file.exists()){
file.mkdirs();
}
//定义输出流,注意必须指定编码
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path+"/"+targetFileName)), UTF_8));
//生成模版
template.process(map, writer);
}catch (Exception e){
log.error("生成异常:{}",e);
}
}
4. 编写Java的代码
构造实体类,通过freemarker将实体类的信息渲染至html
@GetMapping("test")
public Object test() {
Map<String,Object> map = new HashMap<>(16);
List<Poem> list = new ArrayList<>();
list.add(new Poem("赵客缦胡缨,", "吴钩霜雪明。"));
list.add(new Poem("银鞍照白马,", "飒沓如流星。"));
list.add(new Poem("十步杀一人,", "千里不留行。"));
list.add(new Poem("事了拂衣去,", "深藏身与名。"));
map.put("author","李白");
map.put("poem",list);
FreeMarkerUtil.createHtml("poem.ftl","poem.html","侠客行/","侠客行/",map);
return BackMessage.ok(map);
}
实体类:
@Data
public class Poem {
private String first;
private String second;
public Poem(String first, String second) {
this.first = first;
this.second = second;
}
}
5. Html输出
<html>
<head>
<title>啦啦啦啦啦</title>
</head>
<body>
<h1>侠客行</h1>
<p>李白</P>
<p>赵客缦胡缨,吴钩霜雪明。</p></br>
<p>银鞍照白马,飒沓如流星。</p></br>
<p>十步杀一人,千里不留行。</p></br>
<p>事了拂衣去,深藏身与名。</p></br>
</body>
</html>
到此这篇关于SpringBoot如何用java生成静态html的文章就介绍到这了,更多相关java生成静态html内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!