注意:变量中不能有空格
package utils;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import com.jje.common.utils.DateUtils;
public class TemplateUtils {
public static void main(String[] args) {
String json = "{\"Now_Tier\":\"黑卡\",\"Keep_Tier_Point\":\"0\",\"Keep_Tier_Night\":\"0\",\"Card_Number\":\"7700076294\",\"Current_Points\":\"0\",\"Current_Nights\":\"0\",\"Expire_Year\":\"2016\",\"Expire_Month\":\"10\",\"Expire_Day\":\"31\",\"Name\":\"winnie_test4\"}";
final Map<String,Object> map = JsonUtils.jsonToMap(json);
String r = "${Now_Tier}会员完成${Keep_Tier_Point}定级积分或${Keep_Tier_Night}定级次数即可保级。\n" +
"以下是您的会员卡${Card_Number}信息:\n" +
"已完成定级积分:${Current_Points}分\n" +
"已完成定级次数:${Current_Nights}次\n" +
"\n" +
"★10分钟内回复“XF”或直接点击”详情“即可直接续费金卡。如有疑问可拨打1010-1666。\n" +
"详情>";
String sr = TemplateUtils.renderTemplate(r, map);
System.out.println(sr);
}
public static String renderTemplate(String template,Map<String,Object> map) {
while(template.contains("%%")){
template = template.replace("%%","$");
}
map.put("dateUtils",new DateUtils());
map.put("stringUtils",new StringUtils());
// 初始化并取得Velocity引擎
VelocityEngine engine = initProperties();
// 取得velocity的上下文context
VelocityContext context = new VelocityContext();
// 把数据填入上下文
Iterator it = map.keySet().iterator();
while(it.hasNext()){
String key = (String) it.next();
Object value = map.get(key);
context.put(key,value);
}
StringWriter writer = new StringWriter();
engine.evaluate(context, writer, "", template);
return writer.toString();
}
private static VelocityEngine initProperties() {
Properties p = new Properties();
p.setProperty("resource.loader", "class");
p.setProperty("class.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
VelocityEngine ve = new VelocityEngine();
ve.init(p);
return ve;
}
}