Atitit velocity 模板引擎使用法
目录
Context是作为数据容器的,实现是基于HashMap的,模版中用到的变量都必须放到context中,类似于spring中的ModelAndView。没有特殊需求的话可以使用官方推荐的VelocityContext,不支持jdk对象序列化。
VelocityContext构造器默认实现HashMap:
- 单例模式使用: org.apache.velocity.app.Velocity
- 多实例模式使用: org.apache.velocity.app.VelocityEngine
//初始化Velocity
Velocity.init();//创建context
VelocityContext context = new VelocityContext();//添加数据
context.put( "name", new String("Velocity") );//获取模版
Template template = Velocity.getTemplate("templates/helloworld.vm");//Merge 模版和context
StringWriter writer = new StringWriter();template.merge(context, writer);
System.out.println(writer.toString());
//每次创建VelocityEngine对象
VelocityEngine ve = new VelocityEngine();
ve.setProperty( VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this);
ve.init();//创建context
VelocityContext context = new VelocityContext();//添加数据
context.put( "name", new String("Velocity") );//获取模版
Template template = Velocity.getTemplate("templates/helloworld.vm");//Merge 模版和context
StringWriter writer = new StringWriter();template.merge(context, writer);
System.out.println(writer.toString());
public static String getTmpltCalcRzt(String sqlTmplt, VelocityContext context) {
// 初始化并取得Velocity引擎
VelocityEngine ve = new VelocityEngine();
ve.init();
// 取得velocity的模版内容, 模板内容来自字符传
// 输出流
StringWriter writer = new StringWriter();
// 转换输出 con,writer,loigtag,tmplt
ve.evaluate(context, writer, "", sqlTmplt); // 关键方法
String rzt = writer.toString();
return rzt;
}
package org.chwin.firefighting.apiserver.dsl;
import java.io.StringWriter;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
public class velocityUtil {
public static void main(String[] args) {
String t="";
String u_col=" '$uname','$usertype' ";
//创建context
VelocityContext context = new VelocityContext();
//添加数据
context.put( "uname", new String("艾龙") );
context.put( "usertype", new String("维保公司") );
System.out.println( getTmpltCalcRzt(u_col,context) );
}
//@depr
public static String getTmpltCalcRztV2(String sqlTmplt, VelocityContext context) {
// 初始化并取得Velocity引擎
VelocityEngine ve = new VelocityEngine();
ve.init();
// 取得velocity的模版内容, 模板内容来自字符传
// 输出流
StringWriter writer = new StringWriter();
// 转换输出 con,writer,loigtag,tmplt
ve.evaluate(context, writer, "", sqlTmplt); // 关键方法
String rzt = writer.toString();
return rzt;
}
public static String getTmpltCalcRzt(String sqlTmplt, VelocityContext context) {
// 初始化并取得Velocity引擎
VelocityEngine ve = new VelocityEngine();
ve.init();
// 取得velocity的模版内容, 模板内容来自字符传
// 输出流
StringWriter writer = new StringWriter();
// 转换输出 con,writer,loigtag,tmplt
ve.evaluate(context, writer, "", sqlTmplt); // 关键方法
String rzt = writer.toString();
return rzt;
}
}