SpringBoot 利用freemaker生成静态页面
1、
<!-- freemarker模板 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
2、修改配置
spring.freemarker.suffix=.ftl
spring.freemarker.templateEncoding=UTF-8
spring.freemarker.templateLoaderPath=classpath:templates/
spring.freemarker.content-type=text/html
3、在请求controller中加入生成静态页面代码,可自己封装,此处只做演示
/**
* @Description (http://127.0.0.1/abc.html 访问静态页面)
* @param root
* @param request
*/
private void freeMarkerToHtml(Map<String, Object> root, HttpServletRequest request,String id) {
try {
String path = null;
Template temp = configuration.getTemplate("abc.ftl");
// 以classpath下面的static目录作为静态页面的存储目录,同时命名生成的静态html文件名称
String html = TestController.class.getResource("/").toString() + "static/";
File dirfile = new File(html);
if (!dirfile.exists()) {
dirfile.mkdir();
}
path = html + id + ".html";
// String path = this.getClass().getResource("/").toURI().getPath()
// + "static/student.html";
Writer file = new FileWriter(new File(path.substring(path.indexOf("/"))));
temp.process(root, file);
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
@RequestMapping("/testhtml/{id}")
public String gethtml(HttpServletRequest request, Model model,@PathVariable("id") String id) {
String w = "Welcome FreeMarker jinxudong 哈喽!";
Map root = new HashMap();
root.put("w", w);
freeMarkerToHtml(root, request,id);
model.addAttribute("w", w);
return "abc";
}
可以吧对外开放的页面地址写错静态页的地址 不请求数据库 提高并发量
例如:后台请求地址:http://127.0.0.1/testhtml/1000
静态页地址:http://127.0.0.1/1000.html