1.引入依赖
Maven方式
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.7.RELEASE</version>
</dependency>
Grade方式
compile("org.thymeleaf:thymeleaf:3.0.7.RELEASE")
2.引入两个工具类
ApplicationContextHolder
package com.taoweilai.common.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
applicationContext = ctx;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static <T> T getBean(Class<T> clazz){
return applicationContext.getBean(clazz);
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name){
return (T) applicationContext.getBean(name);
}
}
TemplateUtils
package com.taoweilai.common.utils;
import java.io.FileWriter;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
public class TemplateUtils {
@Autowired
public static final TemplateEngine engine = ApplicationContextHolder.getBean(TemplateEngine.class);
/**
* 生成静态文件
* @param freeTempName 模板名称
* @param context 数据内容
* @param outFilePath 输出路径
* @return
*/
public static boolean process(String freeTempName,Context context,String outFilePath) {
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(outFilePath);
engine.process(freeTempName, context,fileWriter);
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
return true;
}
}
3.创建模板
templates/example.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
<span th:text="hello + ${name}"></span>
</body>
</html>
4.在单元测试里面测试
在D中创建test目录
@Test
public void testTemplate() {
String url = "D:/test/";
Context context = new Context();
context.setVariable("name", "world");
TemplateUtils.process("template.html", context, url+"test.html");
}
右击Juint Test运行后
在文件夹中查看已有文件生成
开发页面
生成成功
小程序中使用web-view标签可以嵌套html
<web-view src="D:/test/test.html"></web-view>