Velocity模板使用

阅读更多
import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import com.alibaba.common.logging.Logger;
import com.alibaba.common.logging.LoggerFactory;

public class VelocityUtils {

    private static Logger logger   = LoggerFactory.getLogger(VelocityUtils.class);

    private static String basePath = "vm/"; //resource目录下

    public static String getTemplateContent(String templateName, Map contextMap) {
        //初始化Velocity模板  
        VelocityEngine velocityEngine = new VelocityEngine();

        try {
            Velocity.init();
            Properties properties = new Properties();
            properties.setProperty(Velocity.RESOURCE_LOADER, "class");
            properties.setProperty("class.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            velocityEngine.init(properties);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        //创建一个VeloctiyContext对象  
        VelocityContext context = new VelocityContext();
        //向VelocityContext对象中放入一个键值对  
        for (Map.Entry e : contextMap.entrySet()) {
            context.put(e.getKey(), e.getValue());
        }

        //创建一个输出流  
        StringWriter writer = new StringWriter();
        try {
            //将模板与context中的对象结合,然后输出  
            velocityEngine.mergeTemplate(basePath + templateName, "GBK", context, writer);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return writer.toString();
    }

}

 

你可能感兴趣的:(Velocity模板使用)