经常在一些网站注册以后,收到一封邮件。 下面分析怎样解析mailTemplate. 主要就是利用Matcher中的appendReplacement和appendTail方法。
package com.free.regular;
import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.InvalidPropertiesFormatException; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern;
public class Replacement { /** * source: source */ private static StringBuilder source = null; /** * * Replacement * * @since ver1.00 */ private Replacement(){ } /** * getMessage * @param template * @param params * @return Syring */ public String getMessage(final String template, final Map<String, Object> params) { Pattern pattern = Pattern .compile("(\\$([a-zA-Z][a-zA-Z0-9_-]*))"); Matcher matcher = pattern.matcher(template); StringBuffer result = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(result, "$1" + " : " + params.get(matcher.group(1)).toString().replace("\\", "\\\\").replace("$", "\\$")); } matcher.appendTail(result); return result.toString().replace("\\$", "$").replace("\\\\", "\\"); }
/** * perparedData * * @since ver1.00 */ private void perparedData() { Properties prop = new Properties(); // need to modify String fileName = "C:\\classes\\MailResource.properties";//下面有 FileInputStream fis; try { fis = new FileInputStream(fileName); prop.loadFromXML(fis); } catch (InvalidPropertiesFormatException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } source = new StringBuilder().append(prop.getProperty("issuePassword-content")); } /** * test method * * @param args args * @since ver1.00 */ public static void main(String [] args) { Replacement test = new Replacement(); test.perparedData(); Map<String, Object> params = new HashMap<String, Object>(); params.put("$user_name", "challengehope"); params.put("$temp_password", "1234"); params.put("$temp_password_expiration_date", "2007/08/11"); params.put("$system_name", "Test"); params.put("$system_url", "Http://it_pub:8080/index.do"); System.out.println(test.getMessage(source.toString(), params));
}
}
MailResource.properties //
<?xml version="1.0" encoding="Windows-31J"?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <comment>Mail Properties</comment> <entry key="issuePassword-subject"><![CDATA[ ($system_name)注册会员登录账号 ]]></entry>
<entry key="issuePassword-content"><![CDATA[ 亲爱的会员:您好!
现在您已经成功地注册了,账号如下: 您的注册用户名:$user_name 您的登录密码是:$temp_password 您的密码的有效期限:$temp_password_expiration_date
现在您可以使用这个账号在$system_name登录了! 如果您是刚刚注册,请先了解本站:$system_url
上面的邮件是自动的送信,请不要回复。
$system_name $system_url ]]></entry>
</properties>
如有问题请及时联系QQ:573322952 mail:hufeng@neusoft.com
|
|