最近在做个一个规则匹配,从我多年使用freemarker 的经验决定使用freemarker来做,基于我需要很多规则模板定义,每个规则单独写一个文件太麻烦,于是我感觉freemarker 应该可以使用字符串作为模板,这样我就可以在一个xml定义很多模板,查了查网上资料 大致都是更改templateLoader ,代码如下
package com.venustech.generate;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: skyline{http://my.oschina.net/skyline520}
* Date: 13-1-9
* Time: 下午2:23
* To change this template use File | Settings | File Templates.
*/
public class GenerateRule {
public void generateMain() throws IOException, TemplateException {
/* 在整个应用的生命周期中,这个工作你应该只做一次。 */
/* 创建和调整配置。 */
Configuration cfg = new Configuration();
StringTemplateLoader stringLoader = new StringTemplateLoader();
stringLoader.putTemplate("myTemplate", "rule\n" +
"<#if action??>\n" +
" ${action}\n" +
"</#if>\n" +
"<#if protocol??>\n" +
" ${protocol}\n" +
"</#if>\n" +
"<#if source_ip_address??>\n" +
"\t<#if source_wildcard??>\n" +
" source ${source_ip_address} ${source_wildcard}\n" +
"\t</#if>\n" +
"</#if>\n" +
"<#if destination_ip_address??>\n" +
"\t<#if destination_wildcard??>\n" +
" destination ${destination_ip_address} ${destination_wildcard}\n" +
"\t</#if>\n" +
"</#if>\n" +
"<#if operator??>\n" +
"\t<#if destination_port??>\n" +
" destination_port ${operator} ${destination_port}\n" +
"\t</#if>\n" +
"</#if>");
cfg.setTemplateLoader(stringLoader);
Template temp = cfg.getTemplate("myTemplate","utf-8");
/* 创建数据模型 */
Map root = new HashMap();
root.put("action" ,"deny" );
root.put("protocol" ,"udp" );
root.put("source_ip_address" ,"192.168.56.123" );
root.put("source_wildcard" ,"0.0.0.255" );
root.put("destination_ip_address" ,"192.168.56.123" );
root.put("destination_wildcard" ,"0.0.0.255" );
root.put("operator" ,"gt" );
root.put("destination_port" ,"128" );
Writer out = new StringWriter(2048);
temp.process(root, out);
System.out.println(out.toString().replaceAll("[\\n\\r]", ""));
out.flush();
}
public static void main(String[] args) throws Exception {
GenerateRule html = new GenerateRule();
html.generateMain();
}
}
来源:oschina
链接:https://my.oschina.net/u/156709/blog/133135