FreeMarker 页面静态化 实践

文章介绍了如何利用Freemarker作为模板引擎,通过Configuration对象设置模板路径和编码,加载如news.ftl的模板文件。在JavaServlet环境下,创建数据模型并结合模板生成HTML文件,最终将内容写入到项目webapp目录下的html目录中。
摘要由CSDN通过智能技术生成

通过上述介绍可知 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目录中

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值