模板解析
//构造数据源
Map<String,Object> data=new HashMap<String, Object>();
data.put("siteid", siteInfo.getsiteid());
data.put("name", this.getCurrentUser().account);
data.put("menuid", setSiteID());
//将一个实例化的对象给它
data.put("controller",new SiteinfoController());
//加载framemarker配置
Configuration cfg = new Configuration();
//设置framemarker加载的根路径
cfg.setServletContextForTemplateLoading(request.getSession().getServletContext(),
"sites"+File.separator+ siteInfo.getalias() + File.separator + "install" );//ftl的基本路径
//设置编码
cfg.setEncoding(Locale.getDefault(), "UTF-8");
//生成文件的路径
File f = new File(wirteurl + File.separator + "install" + File.separator + "data.sql");
Writer out = null;
try {
//获取模板
Template t = cfg.getTemplate("data.ftl");
//构建缓存字符输出流,并指定编码格式
out = new BufferedWriter(new FileWriterWithEncoding(f,"UTF-8"));
//赋值
t.process(data, out);
} catch (Exception e) {
// TODO Auto-generated catch block
log.error("execute framemarker error");
e.printStackTrace();
//释放资源
}finally{
if(out != null){
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
后台生成ftl模板,包括变量,以及动态调后台方法
//代码生成ftl模板
//部分代码块
String categorySql = "insert into t_content_category(CATEGORYID,MODULEID,SITEID,NAME,DESCRIPTION,PARENTID,DEPTH,VIEWORDER" +
",ADMINROLES,EDITROLES,VIEWROLES,CREATEDBYUSER,CREATEDDATE,ISACTIVE,URL,COMMENTROLES) values('"
+ category.getCategoryid() + "','"
+ category.getModuleid() + "','" + "${siteid}','"
+ category.getName() + "','"
+ category.getDescription() + "','"
+ category.getParentid() + "','" + category.getDepth()
+ "','" + category.getVieworder() + "','"
+ category.getAdminroles() + "','"
+ category.getEditroles() + "','"
+ category.getViewroles() + "','"
+ "${name}" + "'," + "NOW(),'"
+ category.getIsactive() + "','" + category.getUrl()
+ "','" + category.getCommentroles() + "');";
//动态调用方法设置变量
leftStr += "<#assign var" + count +
"=controller.getUUID()/>";
str = str.replaceAll(moduleLst.get(j).getInstanceid(),
java.util.regex.Matcher.quoteReplacement("${var" + count + "}"));