实现String composeMessage(String template, Map data)通过短消息模板构告消息,要求如下:
模块:
String template="尊敬的客户${customerName}你好!本次消费金额{accountNumber}上的余额为${balance}";
要素:
Map map = new HashMap();
map.put("customerName", "刘恭亮");
map.put("accountNumber", "8888888888888");
map.put("amount", "$50000");
map.put("balance", "$100000.00");
要素合并模板后生成消息:
"尊敬的客户刘恭亮你好!本次消费金额$50000,您帐户8888888888888上的余额为$100000.00";
模块:
String template="尊敬的客户${customerName}你好!本次消费金额{accountNumber}上的余额为${balance}";
要素:
Map map = new HashMap();
map.put("customerName", "刘恭亮");
map.put("accountNumber", "8888888888888");
map.put("amount", "$50000");
map.put("balance", "$100000.00");
要素合并模板后生成消息:
"尊敬的客户刘恭亮你好!本次消费金额$50000,您帐户8888888888888上的余额为$100000.00";
public static void main(String[] args)
{
String template="尊敬的客户${customerName}你好!本次消费金额${accountNumber}上的余额为${balance}";
Map<String,String> map = new HashMap<String,String>();
map.put("customerName", "刘恭亮");
map.put("accountNumber", "8888888888888");
map.put("amount", "$50000");
map.put("balance", "$100000.00");
String str = composeMessage(template, map);
System.out.println(str);
}
public static String composeMessage(String template, Map<String,String> data)
{
for(Map.Entry<String, String> ent : data.entrySet())
{
template = template.replaceAll(Pattern.quote("${" + ent.getKey() + "}"), Matcher.quoteReplacement(ent.getValue()));
}
return template;
}
public class MessageTest { /**
* @param args
*/
public static void main(String[] args) {
String template="尊敬的客户{0}你好!本次消费金{1}上的余额为{2}";
System.out.println(MessageFormat.format(template, "刘共亮",1000,20000));
String template2 = "尊敬的客户%s你好!本次消费金%d上的余额为%d";
System.out.println(String.format(template2, "刘共亮",1000,200000));
}}
System.out.println(MessageFormat.format(template, "刘共亮",1000,20000));
String template2 = "尊敬的客户%s你好!本次消费金%d上的余额为%d";
System.out.println(String.format(template2, "刘共亮",1000,200000)); 这个正解,但是扩展性不佳,楼主可以看看velocity模板方式去实现,扩展性比较好。