package org.whvcse.template;
/**
*
*/
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
/**
* 字符串解析模板类:能解析符合规范的模板字符串.
* @author 武汉软件工程职业学院 计算机应用工程系0701 孟德军
*
* @param <T> 预定义的值类型
*/
public class StringTemplate<T>
{
private String leftDeLimiter = "${";
private String rightDeLimiter = "}";
private static final long serialVersionUID = 1L;
public String parse(String content, Map<String, T> map)
throws Exception {
if (content == null || content.equals("") || map == null
|| map.size() == 0) {
throw new Exception(
"parse content or map<String,T> can't null");
}
String rv = null;
String temp = content;
Iterator<Map.Entry<String, T>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, T> entry = it.next();
String key = this.getLeftDeLimiter() + entry.getKey()
+ this.getRightDeLimiter();
T value = entry.getValue();
int index = temp.indexOf(key);
while (index != -1) {
String leftvalue = temp.substring(0, index);
String rightvalue = temp.substring(index + key.length());
temp = leftvalue + value + rightvalue;
index = temp.indexOf(key);
}
}
return temp;
}
public String parse(String content, Map map, String charset1,
String charset2) throws ParseException {
String s = null;
String temp = parse(content, map);
try {
s = new String(temp.getBytes(charset1), charset2);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return s;
}
public String getLeftDeLimiter() {
return leftDeLimiter;
}
public void setLeftDeLimiter(String leftDeLimiter) {
this.leftDeLimiter = leftDeLimiter;
}
public String getRightDeLimiter() {
return rightDeLimiter;
}
public void setRightDeLimiter(String rightDeLimiter) {
this.rightDeLimiter = rightDeLimiter;
}
}
StringTemplate<String> template=new StringTemplate<String>();
Map<String,String> map=new HashMap<String,String>();
map.put("username","mike");
map.put("password","123456");
String s=template.parse("insert into user(username,password) values(${username},${password})",map);
system.out.println(s);
insert into user(username,password) values(mike,123456)