java渲染字符串模板,也就是說在java字符串模板中設置變量字符串,使用變量去渲染指定模板中設置好的變量字符串。下面介紹4種替換模板方式:html
一、使用內置String.formatjava
String message = String.format("您好%s,晚上好!您目前餘額:%.2f元,積分:%d", "張三", 10.155, 10); System.out.println(message); //您好張三,晚上好!您目前餘額:10.16元,積分:10
二、使用內置MessageFormat 正則表達式
String message = MessageFormat.format("您好{0},晚上好!您目前餘額:{1,number,#.##}元,積分:{2}", "張三", 10.155, 10); System.out.println(message); //您好張三,晚上好!您目前餘額:10.16元,積分:10
三、使用自定義封裝 json
。。。。。
private static Matcher m = Pattern.compile("\\$\\{\\w+\\}").matcher(template);
。。。。。
public static String processTemplate(String template, Map<String, Object> params){ StringBuffer sb = new StringBuffer(); while (m.find()) { String param = m.group(); Object value = params.get(param.substring(2, param.length() - 1)); m.appendReplacement(sb, value==null ? "" : value.toString()); } m.appendTail(sb); return sb.toString(); } public static void main(String[] args){ Map map = new HashMap(); map.put("name", "張三"); map.put("money", String.format("%.2f", 10.155)); map.put("point", 10); message = processTemplate("您好${name},晚上好!您目前餘額:${money}元,積分:${point}", map); System.out.println(message); //您好張三,晚上好!您目前餘額:10.16元,積分:10 }
四、使用模板引擎freemarker segmentfault
首先引入freemarker.jar,這裏以2.3.23版本爲例,若是使用maven的配置pom.xmlwindows
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency>
try { map = new HashMap(); map.put("name", "張三"); map.put("money", 10.155); map.put("point", 10); Template template = new Template("strTpl", "您好${name},晚上好!您目前餘額:${money?string(\"#.##\")}元,積分:${point}", new Configuration(new Version("2.3.23"))); StringWriter result = new StringWriter(); template.process(map, result); System.out.println(result.toString()); //您好張三,晚上好!您目前餘額:10.16元,積分:10 }catch(Exception e){ e.printStackTrace(); }
import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.Version; import java.io.StringWriter; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by cxq on 2018-01-07. */ public class Tpl { public static Configuration cfg; static { cfg = new Configuration(new Version("2.3.23")); } public static void main(String[] args) { Object[] obj = new Object[]{"張三", String.format("%.2f", 10.155), 10}; System.out.println(processFormat("您好%s,晚上好!您目前餘額:%s元,積分:%d", obj)); System.out.println(processMessage("您好{0},晚上好!您目前餘額:{1}元,積分:{2}", obj)); Map map = new HashMap(); map.put("name", "張三"); map.put("money", String.format("%.2f", 10.155)); map.put("point", 10); System.out.println(processTemplate("您好${name},晚上好!您目前餘額:${money}元,積分:${point}", map)); System.out.println(processFreemarker("您好${name},晚上好!您目前餘額:${money}元,積分:${point}", map)); } /** * String.format渲染模板 * @param template 模版 * @param params 參數 * @return */ public static String processFormat(String template, Object... params) { if (template == null || params == null) return null; return String.format(template, params); } /** * MessageFormat渲染模板 * @param template 模版 * @param params 參數 * @return */ public static String processMessage(String template, Object... params) { if (template == null || params == null) return null; return MessageFormat.format(template, params); } /** * 自定義渲染模板 * @param template 模版 * @param params 參數 * @return */ public static String processTemplate(String template, Map<String, Object> params) { if (template == null || params == null) return null; StringBuffer sb = new StringBuffer(); Matcher m = Pattern.compile("\\$\\{\\w+\\}").matcher(template); while (m.find()) { String param = m.group(); Object value = params.get(param.substring(2, param.length() - 1)); m.appendReplacement(sb, value == null ? "" : value.toString()); } m.appendTail(sb); return sb.toString(); } /** * Freemarker渲染模板 * @param template 模版 * @param params 參數 * @return */ public static String processFreemarker(String template, Map<String, Object> params) { if (template == null || params == null) return null; try { StringWriter result = new StringWriter(); Template tpl = new Template("strTpl", template, cfg); tpl.process(params, result); return result.toString(); } catch (Exception e) { return null; } } }
綜合,完整示例:ruby
http://www.weizhixi.com/user/index/article/id/53.htmlapp
/** * 簡單實現${}模板功能 * 如${aa} cc ${bb} 其中 ${aa}, ${bb} 爲佔位符. 可用相關變量進行替換 * @param templateStr 模板字符串 * @param data 替換的變量值 * @param defaultNullReplaceVals 默認null值替換字符, 若是不提供, 則爲字符串"" * @return 返回替換後的字符串, 若是模板字符串爲null, 則返回null */ @SuppressWarnings("unchecked") public static String simpleTemplate(String templateStr, Map<String, ?> data, String... defaultNullReplaceVals) { if(templateStr == null) return null; if(data == null) data = Collections.EMPTY_MAP; String nullReplaceVal = defaultNullReplaceVals.length > 0 ? defaultNullReplaceVals[0] : ""; Pattern pattern = Pattern.compile("\\$\\{([^}]+)}"); StringBuffer newValue = new StringBuffer(templateStr.length()); Matcher matcher = pattern.matcher(templateStr); while (matcher.find()) { String key = matcher.group(1); String r = data.get(key) != null ? data.get(key).toString() : nullReplaceVal; matcher.appendReplacement(newValue, r.replaceAll("\\\\", "\\\\\\\\")); //這個是爲了替換windows下的文件目錄在java裏用\\表示 } matcher.appendTail(newValue); return newValue.toString(); } //測試方法 public static void main(String[] args) { String tmpLine = "簡歷:\n 姓名: ${姓} ${名} \n 性別: ${性別}\n 年齡: ${年齡} \n"; Map<String, Object> data = new HashMap<String, Object>(); data.put("姓", "wen"); data.put("名", "66"); data.put("性別", "man"); data.put("年齡", "222"); System.out.println(simpleTemplate(tmpLine, null, "--")); }
http://wen66.iteye.com/blog/830526maven
static final String jsonStr = "{\"name\":\"11\",\"time\":\"2014-10-21\"}"; static final String template = "親愛的用戶${name},你好,上次登陸時間爲${time}"; static String generateWelcome(String jsonStr,String template){ Gson gson = new Gson(); HashMap jsonMap = gson.fromJson(jsonStr, HashMap.class); for (Object s : jsonMap.keySet()) { template = template.replaceAll("\\$\\{".concat(s.toString()).concat("\\}") , jsonMap.get(s.toString()).toString()); } return template; } public static void main(String[] args) throws IOException { System.out.println(generateWelcome(jsonStr,template)); }
https://segmentfault.com/q/1010000002484866測試
在開發中相似站內信的需求時,咱們常常要使用字符串模板,好比
尊敬的用戶${name}。。。。
裏面的${name}就能夠替換爲用戶的用戶名。
下面使用正則表達式簡單實現一下這個功能:
/** * 根據鍵值對填充字符串,如("hello ${name}",{name:"xiaoming"}) * 輸出: * @param content * @param map * @return */ public static String renderString(String content, Map<String, String> map){ Set<Entry<String, String>> sets = map.entrySet(); for(Entry<String, String> entry : sets) { String regex = "\\$\\{" + entry.getKey() + "\\}"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(content); content = matcher.replaceAll(entry.getValue()); } return content; }
在map裏存儲了鍵值對,而後獲取鍵值對的集合,遍歷集合進行對字符串的渲染
測試:
@Test public void renderString() { String content = "hello ${name}, 1 2 3 4 5 ${six} 7, again ${name}. "; Map<String, String> map = new HashMap<>(); map.put("name", "java"); map.put("six", "6"); content = StringHelper.renderString(content, map); System.out.println(content); }
有兩個變量須要替換,name和six,對應的值分別爲java和6,同時name調用了兩次。
結果:
hello java, 1 2 3 4 5 6 7, again java.
http://www.zgljl2012.com/javazheng-ze-biao-da-shi-shi-xian-name-xing-shi-de-zi-fu-chuan-mo-ban/