首先是freemarker的模板类获取:
①:Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
②:springboot中可以用注解自动注入(本文使用的这种方式)
import freemarker.template.Configuration;//别导入错误的依赖,configuration的类很多的。
@autowire
private Configuration cfg;
①:方法一:适合springBoot项目整合的freemarker中使用,可以直接生成在编译后的target的classes的指定文件中(编译后生成)
private void convertHTML(Map<String,Object> map,HttpServletRequest request) throws IOException, TemplateException {
String realPath = GoodsController.class.getResource("/").getPath();
//使用类加载器获取项目路径,这里得到的路径是运行时的编译路径targe/classes..
//freemarker还有一个加载模板路径的模板类提供的方法,一共三个,参考:文章 尾部
/* -----------------两个方法只有路径不同,只有以上这一句不同--------------------- */
cfg.setDirectoryForTemplateLoading(new File(realPath+"templates"));
//使用模板类设置加载模板的路径,templates是ftl文件的默认访问路径,可以通过application.yml进行freemarker的加载路径配置等。
Template template = cfg.getTemplate("index.ftl");
//读取模板,得到模板的实例。
String fName = "index";//页面名称,可以从前台传递数据来修改。
Writer writer = null;//使用writer进行html文件的生成。
try {
writer = new FileWriter(realPath+"/page/"+fName+".html");
//创建一个io流,生成html文件,../target/classes/page/index.html
template.process(map,writer);
//用模板调用转换的方法,这个方法能生成html文件的同时替换freemarker表达式为静态数据
}finally {
if(writer!=null){
writer.flush();//刷新,使写入立即生效
writer.close();//关流,节约资源(关闭资源)
}
}
}
访问方式:
window.open("index.html");
②:使用转换为html的方法二:适合web项目,项目结构中有webapp目录(请求时生成)
private void convertHTML(Map<String,Object> map,HttpServletRequest request) throws IOException, TemplateException {
String realPath = request.getSession().getServletContext().getRealPath("/");
//得到的路径是:项目名\\src\\main\\webApp\\"
/* ----------------两个方法只有路径不同,只有这一句不同----------------- */
cfg.setDirectoryForTemplateLoading(new File(realPath+"WEB-INF/templates"));
//路径: \\src\\main\\webApp\\WEB-INF\\templates"
Template template = cfg.getTemplate("index.ftl");
String fName = "index";
Writer writer = null;
try {
writer = new FileWriter(realPath+"page/"+fName+".html");//路径: \\src\\main\\webApp\\page\\index.html"
template.process(map,writer);
}finally {
if(writer!=null){
writer.flush();
writer.close();
}
}
}
注意:实际上ftl本省就可以自动转变为html,因为freemarker可是识别html中的指令或表达式,这个的话只需要在配置文件中配置一下后缀即可,相关的代码就不提供了,网络上有很多。HTML页面是不需要配置特殊的视图解析器的,我们的html生成之后可以打包放入Nginx下。html文件的生成路径我们也可以放在我们C盘的temp文件下,这个就不再赘述。
在使用以上方法时生成HTML文件时,可能会出现页面中文乱码的现象,这个的解决方式就是设置一下httpresponse的响应字符集为utf-8和模板配置cfg.setDefaultEncoding("UTF-8")即可。
页面调用的话使用location,如:location=“page/index.html”
freemarker页面路径获取的文章:https://blog.csdn.net/hu_belif/article/details/85721233