字符串模板

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)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值