使用不同模板引擎beetl、FreeMarker、Velocity动态解析sql的方法
1、
String sql = null;
if(null == renderType || renderType.equals(ConstantRender.sql_renderType_beetl)){
if(log.isDebugEnabled()) log.debug("beetl解析sql");
sql = BeetlKit.render(sqlTemplete, param); } else if(renderType.equals(ConstantRender.sql_renderType_freeMarker)){
if(log.isDebugEnabled()) log.debug("FreeMarker解析sql");
sql = ToolFreeMarker.render(sqlTemplete, param); } else if(renderType.equals(ConstantRender.sql_renderType_velocity)){
if(log.isDebugEnabled()) log.debug("Velocity解析sql");
sql = ToolVelocity.render(sqlTemplete, param);
} 2、beetl:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
// package org.beetl.core; import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.beetl.core.resource.StringTemplateResourceLoader;
import org.beetl.ext.fn.GetValueFunction; public class BeetlKit {
public static GroupTemplate gt = null; public BeetlKit() {
} public static String render(String template, Map<String, Object> paras) {
Template t = gt.getTemplate(template);
t.binding(paras);
return t.render();
} public static void renderTo(String template, Writer writer, Map<String, Object> paras) {
Template t = gt.getTemplate(template);
t.binding(paras);
t.renderTo(writer);
} public static void execute(String script, Map<String, Object> paras) {
execute(script, paras, (String[])null);
} public static Map execute(String script, Map<String, Object> paras, String[] locals) {
String start = gt.getConf().getStatementStart();
String end = gt.getConf().getStatementEnd();
StringBuilder sb = new StringBuilder(script.length() + start.length() + end.length());
sb.append(start).append(script);
if (locals != null) {
sb.append("beetlKit(");
String[] var6 = locals;
int var7 = locals.length; for(int var8 = 0; var8 < var7; ++var8) {
String varName = var6[var8];
sb.append("'").append(varName).append("',").append(varName).append("!,");
} sb.setLength(sb.length() - 1);
sb.append(");");
} sb.append(end);
Template t = gt.getTemplate(sb.toString());
t.binding(paras);
HashMap map = new HashMap();
t.binding("beetlKitMap", map);
t.render();
return map;
} public static Map executeAndReturnRootScopeVars(String script) {
String start = gt.getConf().getStatementStart();
String end = gt.getConf().getStatementEnd();
StringBuilder sb = new StringBuilder(script.length() + start.length() + end.length());
sb.append(start).append(script);
sb.append(end);
Template t = gt.getTemplate(sb.toString());
t.render();
Map<String, Integer> idnexMap = t.program.metaData.getTemplateRootScopeIndexMap();
Object[] values = t.ctx.vars;
Map<String, Object> result = new HashMap();
Iterator var8 = idnexMap.entrySet().iterator(); while(var8.hasNext()) {
Entry<String, Integer> entry = (Entry)var8.next();
String name = (String)entry.getKey();
int index = (Integer)entry.getValue();
Object value = values[index];
result.put(name, value);
} return result;
} public static String testTemplate(String template, String initValue) {
Map map = executeAndReturnRootScopeVars(initValue);
String result = render(template, map);
return result;
} public static void main(String[] args) {
String template = "${a}";
String initValue = "var a=1,c=2+1";
String result = testTemplate(template, initValue);
System.out.println(result);
} static {
StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader(); Configuration cfg;
try {
cfg = Configuration.defaultConfiguration();
} catch (IOException var3) {
throw new RuntimeException(var3);
} gt = new GroupTemplate(resourceLoader, cfg);
gt.registerFunction("beetlKit", new GetValueFunction());
gt.setErrorHandler(new ConsoleErrorHandler() {
protected void println(Writer w, String msg) {
try {
w.write(msg);
w.write(10);
} catch (IOException var4) {
var4.printStackTrace();
} } protected void print(Writer w, String msg) {
try {
w.write(msg);
} catch (IOException var4) {
var4.printStackTrace();
} } protected void printThrowable(Writer w, Throwable t) {
t.printStackTrace(new PrintWriter(w));
} protected String getResourceName(String resourceId) {
return resourceId.length() > 10 ? resourceId.substring(0, 10).concat("...") : resourceId;
}
});
}
} 3、FreeMarker:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map; import com.jfinal.log.Log; import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException; /**
* FreeMarker工具类
*/
public abstract class ToolFreeMarker { private static final Log log = Log.getLog(ToolFreeMarker.class); /**
* 渲染模板
* @param templateContent
* @param paramMap
* @return
*/
public static String render(String templateContent, Map<String, Object> paramMap) {
StringWriter writer = new StringWriter();
try {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
cfg.setTemplateLoader(new StringTemplateLoader(templateContent));
cfg.setDefaultEncoding("UTF-8"); Template template = cfg.getTemplate(""); template.process(paramMap, writer);
} catch (IOException e) {
e.printStackTrace();
if(log.isErrorEnabled()) log.error(e.getMessage());
} catch (TemplateException e) {
e.printStackTrace();
if(log.isErrorEnabled()) log.error(e.getMessage());
}
return writer.toString();
} /**
* 生成HTML
* @param tlDirectory tl模板目录
* @param tlName ftl模板
* @param paramMap 参数map
* @param htmlPath 生成HTML存放路径
*/
public static void makeHtml(String tlDirectory, String tlName, Map<String, Object> paramMap, String htmlPath) {
FileOutputStream fileOutputStream = null;
OutputStreamWriter outputStreamWriter = null;
try {
Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
File file = new File(tlDirectory);// .ftl模板目录
configuration.setDirectoryForTemplateLoading(file);
configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_22));
Template template = configuration.getTemplate(tlName, ToolString.encoding); File file2 = new File(htmlPath);// 生成html目录
fileOutputStream = new FileOutputStream(file2);
outputStreamWriter = new OutputStreamWriter(fileOutputStream, ToolString.encoding);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
template.process(paramMap, bufferedWriter);
bufferedWriter.flush();
outputStreamWriter.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
} finally {
if (null != fileOutputStream) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != outputStreamWriter) {
try {
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} } class StringTemplateLoader implements TemplateLoader { private String template; public StringTemplateLoader(String template) {
this.template = template;
if (template == null) {
this.template = "";
}
} public void closeTemplateSource(Object templateSource) throws IOException {
((StringReader) templateSource).close();
} public Object findTemplateSource(String name) throws IOException {
return new StringReader(template);
} public long getLastModified(Object templateSource) {
return 0;
} public Reader getReader(Object templateSource, String encoding) throws IOException {
return (Reader) templateSource;
} } 4、Velocity:
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
import java.util.Set; 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.jfinal.log.Log; /**
* Velocity工具类
*/
public abstract class ToolVelocity { @SuppressWarnings("unused")
private static final Log log = Log.getLog(ToolVelocity.class); /**
* 渲染模板
* @param templateContent
* @param paramMap
* @return
*/
public static String render(String templateContent, Map<String, Object> paramMap) {
// 初始化并取得Velocity引擎
VelocityEngine ve = new VelocityEngine();
ve.init(); // 取得velocity的上下文context
VelocityContext context = new VelocityContext(); Set<String> keys = paramMap.keySet();
for (String key : keys) {
context.put(key, paramMap.get(key));// 把数据填入上下文
} // 输出流
StringWriter writer = new StringWriter(); // 转换输出
ve.evaluate(context, writer, "", templateContent); // 关键方法 return writer.toString();
} /**
* 生成静态html
* @param tlPath 模板路径
* @param paramMap 参数
* @param htmlPath html文件保存路径
*/
public static void makeHtml(String tlPath, Map<String, Object> paramMap, String htmlPath) {
PrintWriter pw = null;
try {
//初始化vm模板
Template template = Velocity.getTemplate(tlPath, "UTF-8"); //初始化上下文
VelocityContext context = new VelocityContext(); //添加数据到上下文中
Set<String> keys = paramMap.keySet();
for (String key : keys) {
context.put(key, paramMap.get(key));
} //生成html页面
pw = new PrintWriter(htmlPath);
template.merge(context, pw);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ResourceNotFoundException e) {
e.printStackTrace();
} catch (ParseErrorException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(pw != null ){
//关闭流
pw.close();
}
}
} }
使用不同模板引擎beetl、FreeMarker、Velocity动态解析sql的方法的更多相关文章
- Visual c++例子,可不使用常规的对话框资源模板的情况下,动态创建对话框的方法
详细说明:Visual c++例子,可不使用常规的对话框资源模板的情况下,动态创建对话框的方法.该方法可以在运行时在内存中直接建立对话框资源,使用起来更为灵活.适用于多个开发项目共享有界面的公用程序模 ...
- Java模板引擎之Freemarker
Freemarker定义: 一款模板引擎 Freemarker是一个web图层组件不是web框架,解析服务端数据到页面 小例子: <#list 集合 as item> list标签对集合进 ...
- 阅读优秀的JAVA模板引擎Beetl的使用说明有感
由于项目需要,对包括Beetl在内的JAVA模板引擎技术进行了学习 Beetl是由国人李家智(昵称闲大赋)开发的一款高性能JAVA模板引擎,对标产品是Freemaker 感慨于近几年国内开源项目的蓬勃 ...
- Java模板引擎之Freemarker 学习笔记 一
什么是Freemarker Freemarker是模板引擎,不是Web框架,只是视图层的组件,官网是 https://freemarker.apache.org/ Freemarker原理 数据模型+ ...
- vue系列---Mustache.js模板引擎介绍及源码解析(十)
mustache.js(3.0.0版本) 是一个javascript前端模板引擎.官方文档(https://github.com/janl/mustache.js) 根据官方介绍:Mustache可以 ...
- velocity模板引擎学习(2)-velocity tools 2.0
使用velocity后,原来的很多标签无法使用了,必须借助velocity tools来完成,目前velocity tools最新版本是2.0,下面是velocity tools的一些注意事项: 1. ...
- Java模板引擎之freemarker简介
- SQL动态配置,动态解析SQL
在项目中使用SQL动态配置的方式可以让后期的维护和发布后的修改变得更加方便,无论使用那种配置方式都离不开解析成最终真正能执行的SQL.下面代码就是一种比较简单的处理方法,SQL的参数以##括起来. 1 ...
- shell动态解析sql的binlog
#!/usr/bin #设置数据库连接 conn='mysql -hhost -Pport -uusername -ppassword' #获取最新的binlog文件 logfile=$($conn ...
随机推荐
- Android 虚拟键盘弹出把底部栏顶上去的解决办法
在AndroidManifest中使用ActivityGroup的activity中加上:android:windowSoftInputMode="adjustPan"
- MathType怎么编辑半开半闭区间
数学中的公式有很多,涉及到各种各样的样式,这些公式都会用到不同的符号,每一个符号用在不同数学问题的公式中,都会有其特定的意义,比如括号.括号这个符号在除了能够表示优先运算之外,还可以代表区间的意思,小 ...
- mysql5.7 启动报发生系统错误2
1. http://dev.mysql.com/downloads/mysql/ 下载mysql5.7 zip包 2. 下载好后解压文件,解压的内容如图,您可以把内容解压到想要的位置 ...
- 理解linux 块, i节点
https://blog.csdn.net/zdf19/article/details/54424880 https://www.cnblogs.com/hnrainll/archive/2012/0 ...
- 修改centos的时间,解决时间比本地实际时间快了8小时
1.vi /etc/sysconfig/clock #编辑文件ZONE="Asia/Shanghai"UTC=false #设置为false,硬件时钟不于utc时间一致ARC=fa ...
- Java通过复选框控件数组实现添加多个复选框控件
编写程序,通过复选框控件数组事先选择用户爱好信息的复选框,在该程序中,要求界面中的复选框数量可以根据指定复选框名称的字符串数组的长度来自动调节. 思路如下: 创建JPanel面板对象: 使用JPane ...
- JSON XSS
漏洞实例一: 1.在更新用户信息,修改联系电话,抓包绕过前端20个字符限制,Payload为 111<img src=1 onerror=alert(1)> 2.更新后,访问json 3. ...
- python cookie
http://www.jayconrod.com/posts/17/how-to-use-http-cookies-in-python
- 使用 urllib 发送请求
urllib.request.urlopen(url, data=None, timeout=n) 用于发送HTTP请求并得到响应内容 In []: import urllib.request In ...
- ScaleType属性
FIT_CENTER 把原图按照比例放大缩小到ImageView的高度,显示在ImageView的center(中部/居中显示). 1 2 CENTER_CROP 会拉伸图片以原图填满ImageV ...