VelocityUtils

/**
 * Copyright (c) 2005-2010 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: VelocityUtils.java 1211 2010-09-10 16:20:45Z calvinxiu $
 */
package com.juqi.group.common.util;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import com.juqi.group.service.ServiceException;

/**
 * 使用Velocity生成内容的工具类.
 * 
 */
public class VelocityUtils {

	static {
		try {
			Velocity.setProperty("input.encoding", "UTF-8");
			Velocity.setProperty("output.encoding", "UTF-8");
			Velocity.setProperty("directive.foreach.counter.name", "c");
			Velocity.init();
		} catch (Exception e) {
			throw new RuntimeException(
					"Exception occurs while initialize the velociy.", e);
		}
	}

	/**
	 * 渲染内容.
	 * 
	 * @param template
	 *            模板内容.
	 * @param model
	 *            变量Map.
	 * @throws IOException 
	 */
	public static String render(String template, Map<String, ?> model) throws ServiceException {
		try {
			VelocityContext velocityContext = new VelocityContext(model);
			StringWriter result = new StringWriter();
			Velocity.evaluate(velocityContext, result, "", template);
			return result.toString();
		}
		catch (Exception e) {
			throw new ServiceException("解析模板异常", e);
			
		}
	}

	private static VelocityEngine velocityEngine() {
		VelocityEngine ve = new VelocityEngine();
		// 写绝对路径
		ve.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH,
				"src/main/resources");
		ve.setProperty("input.encoding", "UTF-8");
		ve.setProperty("output.encoding", "UTF-8");
		ve.setProperty("directive.foreach.counter.name", "c");
		try {
			ve.init();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return ve;

	}

	public static String parse(Map<String, Object> map) {
		VelocityContext context = new VelocityContext(map);

		try {
			Template template = velocityEngine().getTemplate("index.vm");

			StringWriter sw = new StringWriter();

			if (template != null)
				template.merge(context, sw);
			sw.flush();
			sw.close();
			return sw.toString();
		} catch (ResourceNotFoundException e) {
			e.printStackTrace();
		} catch (ParseErrorException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {

		List<String> list = new ArrayList<String>();
		list.add("1");
		list.add("2");
		list.add("3");
		list.add("4");
		list.add("5");
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("list", list);
		System.out.println(parse(m));
	}
}

你可能感兴趣的:(java,apache,C++,c,velocity)