最近学习一个项目是用的Freemaker输出静态HTML,随着越来越多的项目使用SpringBoot那么使用SpringBoot官方推荐的Thymeleaf生成静态文件是怎么做的呢,话不多说直接上代码。
1.引入Starter是必须的
<!-- 我的springboot版本2.1.2.RELEASE,对应thymeleaf3.0.11.RELEASE-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.1.12</version>
</dependency>
2.在resources/templates目录下创建模板,模板如下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>测试</title>
</head>
<body>
<div>
<h2 th:text="${hello}"></h2>
</div>
</body>
</html>
3.代码
@RestController
public class LearnController {
@GetMapping("/thymeleaf/{msg}")
public void learn(@PathVariable String msg) throws IOException {
//创建模版加载器
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setPrefix("templates/"); //模板文件的所在目录
resolver.setSuffix(".html"); //模板文件后缀
//创建模板引擎
TemplateEngine templateEngine = new TemplateEngine();
//将加载器放入模板引擎
templateEngine.setTemplateResolver(resolver);
//创建字符输出流并且自定义输出文件的位置和文件名
FileWriter writer = new FileWriter("F:/learn/index.html");
//创建Context对象(存放Model)
Context context = new Context();
//放入数据
context.setVariable("hello",msg);
//创建静态文件,"text"是模板html名字
templateEngine.process("text",context,writer);
}
}
4.浏览器输入http://localhost:8080/thymeleaf/请一定好好加油
得到结果:
另外大家如果遇到报错Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template [thymeleaf/请一定要好好加油], template might not exist or might not be accessible by any of the configured Template Resolvers] with root cause很有可能是因为使用了@Controller而应该用@RestController注解应该就好了.
------------------------------------ 感谢查看,如果有什么问题请留言(2019年3月3号)