velocity学习

 例子1:

 

package nc.jonathan.velocity;
import java.io.StringWriter;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
/**
 *

第一个velocity学习类

 *
 *

采用默认初始化设置,解析字符串, 输出到字符串

 *
 * Create on 2006-4-3 10:12:38
 *
 * @author Jonathan Q. Bo
 * @version 1.0 valocity study
 */
public class QuickStartExample {
 public static void main(String[] args){
  try {
   /* 初始化运行时引擎, 默认初始化 */
   Velocity.init();
   
   /* 建立context, 并放入数据*/
   VelocityContext context = new VelocityContext();
   context.put("project","jonathan's velocity");
   context.put("name","first example");
   
   /* 解析后数据的输出目标,java.io.Writer的子类 */
   StringWriter w = new StringWriter();
   
   /* 此处采用字符串模版 */
   String s = "We are using string velocity to generate $project $name";
   
   /* 进行解析 */
   Velocity.evaluate(context,w,"mystring",s);
   System.out.println(w);
  } catch (ResourceNotFoundException e1) {
   System.out.println("## 源文件不存在!");
   e1.printStackTrace();
  } catch (ParseErrorException e2) {
   System.out.println("## 解析文件错误!");
   e2.printStackTrace();
  } catch (MethodInvocationException e3) {
   System.out.println("## 方法调用异常!");
   e3.printStackTrace();
  } catch (Exception e4){
   System.out.println("## 其他错误!");
   e4.printStackTrace();
  }
 }
}
输出结果
We are using string velocity to generate jonathan's velocity first example

 

 

 

例子2:

String result;

Map<String, Object> map = new HashMap<String, Object>();

            map.put("uri", uriBrokerService);

String instring="$uri.getURIBroker('mlproductpostingServer')/posting/postMlProduct.htm";

          

VelocityContext context = new VelocityContext(map );

        StringWriter writer = new StringWriter();

        ve.evaluate(context, writer, LOG_TAG, instring);

 

        result= writer.getBuffer().toString();

你可能感兴趣的:(velocity)