/** * 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)); }}
VelocityUtils
最新推荐文章于 2024-11-30 09:43:50 发布