java 字符串模板解析
1. MessageFormat优点:不需要映入第三方类库,门槛低
缺点:使用序号来和后面参数约定,耦合性比较大,维护成本高,可重用性不高
对于所有信息都放到bean中,需要后期将对象一个个的get属性,开发代码比较多
System.out.println(MessageFormat.format("我是{0},我来自{1},今年{2}岁", "中国人", "北京", "22"));
2. freemarker
优点:重用性高,只要传入待替换string及数据对象,可以完成所有替换
可维护性高,模板修改,替换代码不需要变更
缺点:bean属性删除的时候替换代码不会报错,导致原值直接输出 需要映入第三方类库 try { Configuration cfg = new Configuration(); StringTemplateLoader stl =new StringTemplateLoader(); stl.putTemplate("", "hello:${name}"); cfg.setTemplateLoader(stl); Template template = cfg.getTemplate(""); Bean b = new Bean(); b.setName("aaa"); StringWriter writer = new StringWriter(); template.process(b, writer); System.out.println(writer.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
3。 Velocity
优点:键值对的形式,由于MessageFormat不需要维护序号
缺点:重用性不高;需要映入第三方类库
Context context= new VelocityContext(); context.put("name", "aaa"); StringWriter sw = new StringWriter(); try { Velocity.evaluate(context, sw, "velocity", "hello:${name}"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(sw.toString());
页:
[1]