首页 > 代码库 > 使用Velocity

使用Velocity

 1 package com.isoftstone.iics.bizsupport.sms.common.utils;
 2 
 3 import java.io.IOException;
 4 import java.io.StringWriter;
 5 import java.util.HashMap;
 6 import java.util.Map;
 7 
 8 
 9 import org.apache.velocity.VelocityContext;
10 import org.apache.velocity.app.VelocityEngine;
11 import org.apache.velocity.exception.VelocityException;
12 import org.apache.velocity.runtime.RuntimeConstants;
13 import org.apache.velocity.runtime.log.Log4JLogChute;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
16 
17 import org.springframework.stereotype.Component;
18 import org.springframework.ui.velocity.VelocityEngineFactory;
19 
20 import com.isoftstone.iics.bizsupport.sms.web.constant.IpWhiteList;
21 
22 @Component("VelocityUtils")
23 public class VelocityUtils {
24     
25     private static final Logger logger=LoggerFactory.getLogger(IpWhiteList.class);
26     public static String LOGGER_NAME = "fenghao";
27     public static String assemblyTemplate(Map<String,String> data ,String message){
28         VelocityEngineFactory factory=new VelocityEngineFactory();
29         VelocityEngine ve=null;
30         try {
31             ve = factory.createVelocityEngine();
32         } catch (VelocityException e) {
33             e.printStackTrace();
34             logger.error("\nvelocity Exception and "+e.getMessage());
35         } catch (IOException e) {
36             e.printStackTrace();
37             logger.error("\nio Ecception "+e.getMessage());
38         }
39         VelocityContext context=new VelocityContext();
40         for(Map.Entry<String, String> entry:data.entrySet()){
41             String key=entry.getKey();
42             String value=http://www.mamicode.com/entry.getValue();
43             context.put(key, value);
44         }
45         StringWriter sw=new StringWriter();
46         ve.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, 
47                "org.apache.velocity.runtime.log.Log4JLogChute");
48         ve.setProperty(Log4JLogChute.RUNTIME_LOG_LOG4J_LOGGER, LOGGER_NAME);
49         boolean evaluate = ve.evaluate(context, sw, "",message);
50         if(evaluate){
51             sw.flush();
52             return sw.toString();
53         }
54         return null;
55     }
56     @org.junit.Test
57     public void Test(){
58         Map<String,String> data=http://www.mamicode.com/new HashMap<String,String>();
59         data.put("name", "冯浩");
60         data.put("phone", "18295789020");
61         String message="${name}在哪呢,你的电话是${phone}";
62         String result = VelocityUtils.assemblyTemplate(data, message);
63         System.out.println("\nresult is "+result);
64         
65     }
66     
67 
68 }

在项目中使用该(evaluate)静态的方法的时候,项目启动的时候会报异常,所以设置了运行时日志类的指定(可能是依赖的日志包的版本不同导致的)

使用Velocity