通过上述介绍可知 Freemarker 是一种基于模板的、用来生成输出文本的通用工具,所以 我们必须要定制符合自己业务的模板,然后生成自己的 html 页面。Freemarker 是通过freemarker.template.Configuration 这个对象对模板进行加载的(它也处理创建和缓存预 解析模板的工作),然后我们通过getTemplate 方法获得你想要的模板,有一点要记住freemarker.template.Configuration 在你整个应用必须保证唯一实例。
定义模板
加载模板
public class NewsServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Configuration configuration=new Configuration();
configuration.setServletContextForTemplateLoading(getServletContext(),"/template");
configuration.setDefaultEncoding("UTF-8");
Template template=configuration.getTemplate("news.ftl");
Map<String,Object> map=new HashMap<>();
map.put("title","力量");
map.put("source","经济日报");
map.put("pubTime","2023");
map.put("content","我是内容");
String basePath=req.getServletContext().getRealPath("/");
File htmlFile=new File(basePath+"/html");
if(!htmlFile.exists()){
htmlFile.mkdir();
String fileName=System.currentTimeMillis()+".html";
File file=new File(htmlFile,fileName);
FileWriter writer=new FileWriter(file);
try {
template.process(map,writer);
} catch (TemplateException e) {
e.printStackTrace();
}finally{
writer.flush();
writer.close();
}
}
}
}
效果:
生成对应的html文件
浏览器地址栏输入:
http://localhost:8989/news
生成的文件存放在当前项目的webapp目录下的html目录中