首页>代码>自己在项目中写的简单的仿 freemarker 模板引擎工具 V2 版本,支持迭代 template4javaniu>/template4javaniu/TemplateUtils.java
/*
* Copyright 2012-2013 The Haohui Network Corporation
*/
package com.haohui.baidamei.client.web.json.template;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <pre>
* 模板资源读取工具
* </pre>
*
* @project baidamei
* @author cevencheng <cevencheng@gmail.com>
* @create 2012-11-24 下午9:21:51
*/
public class TemplateUtils {
public static URL getResource(String name) {
return TemplateUtils.class.getResource(name);
}
/**
* 默认编码: UTF-8 t1: 支持模板注释 和 jsp 代码级别注释 <#-- freemarker 注释 --> <%!-- jsp 代码级别
* 注释 -->
*
* @param templateName
* @param encoding
* @return
* @throws URISyntaxException
*/
public static String processTemplateIntoString(String templateName) {
return processTemplateIntoString(templateName, "utf8");
}
/**
* t1: 支持模板注释 和 jsp 代码级别注释 <#-- freemarker 注释 --> <%!-- jsp 代码级别 注释 -->
*
* @param templateName
* @param encoding
* @return
* @throws URISyntaxException
*/
public static String processTemplateIntoString(String templateName, String encoding) {
URL url = TemplateUtils.class.getResource(templateName);
if (null == url) {
throw new RuntimeException("模板文件[com/haohui/baidamei/client/web/json/template" + templateName + "]不存在");
}
if (null == encoding) {
encoding = "utf-8";
}
encoding = encoding.trim();
StringBuilder str = new StringBuilder();
FileInputStream fs = null;
InputStreamReader isr = null;
String content = null;
try {
fs = new FileInputStream(new File(url.toURI()));
isr = new InputStreamReader(fs, encoding);
// 方法2:自己实现 buffer
char[] buffer = new char[1024];
int len = 0;
while ((len = isr.read(buffer)) > 0) {
str.append(buffer, 0, len);
}
content = str.toString();
String parttern = "<#--[\\w\\W\r\\n]*?-->";
Pattern p1 = Pattern.compile(parttern);
Matcher m1 = p1.matcher(content);
content = m1.replaceAll(""); // 去掉模板注释
return content;
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e.getCause());
} finally {
try {
isr.close();
fs.close();
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e.getCause());
}
}
}
public static String processTemplateIntoString(String templateName, String encoding, Map<String, Object> model) {
URL url = TemplateUtils.class.getResource(templateName);
if (null == url) {
throw new RuntimeException("模板文件[com/haohui/baidamei/client/web/json/template" + templateName + "]不存在");
}
if (null == encoding) {
encoding = "utf-8";
}
encoding = encoding.trim();
StringBuilder str = new StringBuilder();
FileInputStream fs = null;
InputStreamReader isr = null;
String content = "";
try {
fs = new FileInputStream(new File(url.toURI()));
isr = new InputStreamReader(fs, encoding);
// 方法2:自己实现 buffer
char[] buffer = new char[1024];
int len = 0;
while ((len = isr.read(buffer)) > 0) {
str.append(buffer, 0, len);
}
content = str.toString();
content = content.replaceAll("\r|\n", ""); //去掉回车、换行
String parttern = "<#--[\\w\\W\r\\n]*?-->";
Pattern p1 = Pattern.compile(parttern);
Matcher m1 = p1.matcher(content);
content = m1.replaceAll(""); // 去掉模板注释
// 处理模板变量 #{name} -->> 成功
if (model.size() > 0) {
for (Map.Entry<String, Object> entry : model.entrySet()) {
String regex = "#\\{" + entry.getKey() + "\\}";
content = content.replaceAll(regex, entry.getValue().toString());
}
}
// 处理 shell 脚本
// <#foreach var="entry"items="userlist"><li>${entry.xxx}</li><li>${entry.eee}</li><li>${entry.ddd}</li></#foreach>
String regex = "(?i)<#foreach var=\"([^>]+)\" items=\"([^>]+)\">(.+?)</#foreach>";
String regex2 = "(?i)(#\\{[^>]+\\})";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(content);
String var = "";
String items = "";
String xhcontent = "";
List<String> vallist = new ArrayList<String>();
while (m.find()) {
System.out.println(m.groupCount());
var = m.group(1);
items = m.group(2);
xhcontent = m.group(3);
System.out.println(var);
System.out.println(items);
System.out.println(content);
Pattern p2 = Pattern.compile(regex2);
Matcher m2 = p2.matcher(xhcontent);
while (m2.find()) {
System.out.println("m2" + m2.groupCount());
System.out.println("m2.li: " + m2.group());
vallist.add(m2.group());
}
}
System.out.println(vallist);
///
// 处理循环
List<Object> listdata = (List<Object>) model.get(items);
StringBuilder sb = new StringBuilder();
if (listdata != null && listdata.size() > 0) {
String template = xhcontent;
for (Object object : listdata) {
// #{entry.xxx}, #{entry.eee}, #{entry.ddd}
// 处理每一个模板变量
for (String temp : vallist) {
String name = temp.substring(temp.indexOf("#") + 2, temp.lastIndexOf("}"));
System.out.println("name=" + name);
if (name.contains(".")) { // 对象表达式 invoke 对象
String[] arr = name.split("\\.");
if (!var.equals(arr[0])) {
System.out.println("不是引用的循环变量");
// entry.xxx | user.age
object = model.get(arr[0]);
}
// 方法名 xxx
String methodname = "get" + arr[1].substring(0, 1).toUpperCase() + arr[1].substring(1);
System.out.println("方法名:" + methodname);
Class<?> clazz = object.getClass();
Method method = clazz.getDeclaredMethod(methodname, null);
method.setAccessible(true);
System.out.println(method);
Object value = method.invoke(object, null); //invoke method
template = template.replaceAll("#\\{"+ name +"\\}", value.toString());
} else {
Object value = model.get(name);
template = template.replaceAll("#\\{"+ name +"\\}", value.toString());
}
}
sb.append(template);
}
}
content = m.replaceAll(sb.toString());
return content;
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e.getCause());
} finally {
try {
isr.close();
fs.close();
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e.getCause());
}
}
}
private static String getForeach(final String s) {
String regex;
String title = "";
final List<String> list = new ArrayList<String>();
regex = "(<foreach[\\s\\S]*?>(.*?)</foreach>)";
final Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
final Matcher ma = pa.matcher(s);
while (ma.find()) {
String item = ma.group();
System.out.println("item:" + item);
// Matcher m =
// Pattern.compile("items=\"((.*?)\">?(.*?)(\"|foreach>))").matcher(item);
// //匹配src
// while(m.find()){
// System.out.println(m.groupCount());
// String li = m.group(0);
// System.out.println("li:g0" + li + ", g1:" + m.group(1) + ", g2" +
// m.group(2) + ", g3:" + m.group(3));
// }
list.add(item);
}
for (int i = 0; i < list.size(); i++) {
title = title + list.get(i);
}
// return outTag(title);
return title;
}
public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
// processTemplateIntoString("sss", null);
String text = "<#foreach var=\"entry\" \r\n\t items=\"userlist\">";
text += "<li>${entry.xxx}</li>";
text += "<#/foreach>";
text += "<h1 src=\"xxxx.com.cn/img.jpg\">这是标题以及</h1><h2>这是二级标题</h2>";
// text = "<script>var i = 10; j= 10; alert('hello world');</script>";
// text = "<title>标题</title>";
// String parttern = "(<script[^>]*?>)(.*?)<\\/script>";
// String regex =
// "(<#[\\s\\S]*?>)|(<#/[\\s\\S]*?>|(<#[\\s\\S]*?>(<#[\\s\\S]*?)<#/foreach>))";
// String regex = "<h[1-9][\\s\\S]*?>[\\s\\S]*?</h[1-9]>"; OK
// String regex = "(<#foreach[\\s\\S]*?>)([\\s\\S]*?)<#/foreach>";
// Pattern p = Pattern.compile(regex);
// Matcher m = p.matcher(text);
// while (m.find()) {
// System.out.println("li:" + m.group());
// }
Map<String, Object> map = new HashMap<String, Object>();
Bean bean = new Bean("101", "小叶子");
Bean bean2 = new Bean("102", "石头");
List<Bean> list = new ArrayList<Bean>(2);
list.add(bean);
list.add(bean2);
map.put("userlist", list);
String s = "<#foreach var=\"entry\" items=\"userlist\"><li>#{entry.id}</li><li>#{entry.value}</li></#foreach>";
String regex = "(?i)<#foreach var=\"([^>]+)\" items=\"([^>]+)\">(.+?\\s)</#foreach>";
String regex2 = "(?i)(#\\{[^>]+\\})";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
String var = "";
String items = "";
String content = "";
List<String> vallist = new ArrayList<String>();
while (m.find()) {
System.out.println(m.groupCount());
var = m.group(1);
items = m.group(2);
content = m.group(3);
System.out.println(var);
System.out.println(items);
System.out.println(content);
Pattern p2 = Pattern.compile(regex2);
Matcher m2 = p2.matcher(s);
while (m2.find()) {
System.out.println("m2" + m2.groupCount());
System.out.println("m2.li: " + m2.group());
vallist.add(m2.group());
}
}
System.out.println(vallist);
// 处理循环
List<Object> listdata = (List<Object>) map.get(items);
StringBuilder sb = new StringBuilder();
if (listdata != null && listdata.size() > 0) {
String template = content;
for (Object object : listdata) {
// #{entry.xxx}, #{entry.eee}, #{entry.ddd}
// 处理每一个模板变量
for (String temp : vallist) {
String name = temp.substring(temp.indexOf("#") + 2, temp.lastIndexOf("}"));
System.out.println("name=" + name);
if (name.contains(".")) { // 对象表达式 invoke 对象
String[] arr = name.split("\\.");
if (var.equals(arr[0])) {
// 方法名 xxx
String methodname = "get" + arr[1].substring(0, 1).toUpperCase() + arr[1].substring(1);
System.out.println("方法名:" + methodname);
Class<?> clazz = object.getClass();
Method method = clazz.getDeclaredMethod(methodname, null);
method.setAccessible(true);
System.out.println(method);
Object value = method.invoke(object, null); //invoke method
template = template.replaceAll("#\\{"+ name +"\\}", value.toString());
} else {
System.out.println("不是引用的循环变量");
}
} else {
Object value = map.get(name);
template = template.replaceAll("#\\{"+ name +"\\}", value.toString());
}
}
sb.append(template);
}
}
System.out.println(sb.toString());
}
}

最近下载
最近浏览