使用不同模板引擎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 paras) {
Template t = gt.getTemplate(template);
t.binding(paras);
return t.render();
}

public static void renderTo(String template, Writer writer, Map paras) {
Template t = gt.getTemplate(template);
t.binding(paras);
t.renderTo(writer);
}

public static void execute(String script, Map paras) {
execute(script, paras, (String[])null);
}

public static Map execute(String script, Map 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 idnexMap = t.program.metaData.getTemplateRootScopeIndexMap();
Object[] values = t.ctx.vars;
Map result = new HashMap();
Iterator var8 = idnexMap.entrySet().iterator();

while(var8.hasNext()) {
Entry 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 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 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 paramMap) {
// 初始化并取得Velocity引擎
VelocityEngine ve = new VelocityEngine();
ve.init();

// 取得velocity的上下文context
VelocityContext context = new VelocityContext();

Set 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 paramMap, String htmlPath) {
PrintWriter pw = null;
try {
//初始化vm模板
Template template = Velocity.getTemplate(tlPath, "UTF-8");

//初始化上下文
VelocityContext context = new VelocityContext();

//添加数据到上下文中
Set 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();
}
}
}

}



转载于:https://www.cnblogs.com/YuyuanNo1/p/9810767.html

你可能感兴趣的:(使用不同模板引擎beetl、FreeMarker、Velocity动态解析sql的方法)