Simple implementation
For Java string placeholder replacements, the professional approach is to use the String.Format and Messageformat.format features, which provide a simple, regular implementation based string placeholder implementation
public static string TPL (string tplstr,map<string, object> data) {
Matcher m=pattern.compile ([\\{.] *) \ \} "). Matcher (TPLSTR);
while (M.find ()) {
String group=m.group ();
group= group.replaceall ("\\{|\\}", "");
String value= "";
if (Null!=data.get (group)) {
value=string.valueof (Data.get (group));
}
Tplstr=tplstr.replace (M.group (), value);
}
return tplstr;
}
Using template engines such as Freemarker
Private String Defaultcharacter = "UTF-8";
Private Configuration cfg;
Public freemarkerutils () {cfg = new Configuration ();
Cfg.setdefaultencoding (Defaultcharacter);
Cfg.settagsyntax (Configuration.auto_detect_tag_syntax); Public String generatestring (map<string, object> data, String tplstr) {string result
= NULL;
String name= "MYSTRTPL";
try {stringtemplateloader stringtemplateloader= new Stringtemplateloader ();
Stringtemplateloader.puttemplate (name, TPLSTR);
Cfg.settemplateloader (Stringtemplateloader);
Template Template = cfg.gettemplate (Name,defaultcharacter);
StringWriter out = new StringWriter ();
Template.process (data, out);
Out.flush ();
result= out.tostring ();
Out.close ();
catch (Exception e) {e.printstacktrace (); return result; }