使用不同模板引擎beetl、FreeMarker、Velocity動態解析sql的方法
阿新 • • 發佈:2018-11-11
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();
}
}
}
}