Velocity .vm 生成静态页面

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

public class HtmlUtil {

    /**
     * 将数据与模版板进行合并
     * @param writer        输出流
     * @param map           数据
     * @param vmName  模板文件名
     * @param encoding      编码格式
     * @throws Exception
     */
    public static void generate(Writer writer, Map<String, Object> map,
                                 String encoding,String vmRelPath,String vmName) throws Exception {
        Properties p = new Properties();
        p.setProperty("file.resource.loader.path", vmRelPath);
        VelocityEngine engin = new VelocityEngine();
        engin.init(p);
        Template template = engin.getTemplate(vmName, encoding);
        Context context = new VelocityContext();
        for(Iterator<String> i = map.keySet().iterator(); i.hasNext(); ) {
            String key = i.next();
            context.put(key, map.get(key));
        }
        template.merge(context, writer);
    }

    /**
     * 合并数据,生成文件
     * @param file        文件
     * @param map         数据
     * @param encoding    编码
     * @throws Exception
     */
    public static void merge(File file, Map<String, Object> map, String encoding,String vmPath,String vmName) throws Exception {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding));
            generate(bw, map, encoding,vmPath,vmName);
        } finally {
            bw.close();
        }
    }

    public static void main(String[] args) throws Exception{
        //生成静态文件位置
        File file = new File("D:/web/", "test.html");
        Map<String, Object> map = new HashMap<String, Object>();
        //模版文件所需要的数据
        map.put("special", "test");
        //模版文件
        merge(file, map, "UTF-8","D:/special/","special.vm");
    }
}

注:
上述代码通过velocity文件生成静态html文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值