Freemarker 是一种基于模板的,用来生成输出文本的通用工具,所以我们必须要定制符合自己业务的模板,然后生成自己的文本(html页面,string字符串,xml文本等等)。Freemarker是通过freemarker.template.Configuration这个对象对模板进行加载的(它也可以处理创建和缓存预解析模板的工作),然后我们通过getTmeplate方法获取你想要的模板,准备模板数据,并通过process()将模板数据填充到输入流中,具体如下:
定义模板
准备ftl文件:news.ftl
<html>
<title>${title!}</title>
<meta charset="uft-8">
<head></head>
<body>
<title>${title!}</title>
</body>
</html>
加载模板
可以是配置文件或者在具体需要的地方写入
import freemarker.template.Configuration;
public class Test extends HttpServlet{@overrideprotected void service(HttpServlerRequest req,HttpServletResponse resp) throws ServletException,IOException{@AutowritedConfiguration configuration; //模板配置对象//加载文件路径configuraiton.setServletContextTemplateLoading(getServletContext(),"/template");//设置模板的编码格式configuration.setDefaultEncoding("utf-8");//加载模板文件,获取模板对象 ftl文件名Template template = configuration.getTemplate("news.ftl"); //加载数据模型Map<String,Object> map = new HashMap<>();map.put("title","新闻");//获取项目所在根目录String basePath = req.getServletContext().getRealPath("/");//设置页面存放路径File htmlFile = new File(basePath+"/ftl");//判断目录是否存在if(!htmlFile.exists()){htmlFile.mkdir();}//获取文件名 实际运用中尽量使用唯一标识进行命名,如:idString fileName = System.currentTimeMills()+".html";File file = new File(htmlFile,fileName);//获取文件输出流FileWriter writer = new FileWriter(file);//StringWriter writer = new StringWriter();//System.out.println(writer.toString());//将模型数据填充到模板中template.process(map,writer);writer.flush();writer.close();}
}
运行完成可以到指定目录查找该文件是否存在,页面静态化针对不经常变化的页面实现,当访问某一详情页面时,如果本地存在该详情页面则直接访问本地,否则访问数据库获取数据生成页面,使用静态化页面大大提高了访问效率。