Java string Placeholder replacement string placeholder implementation (Java Simple template rendering implementation)

Source: Internet
Author: User
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; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.