/
java渲染字符串模板,也就是说在java字符串模板中设置变量字符串,使用变量去渲染指定模板中设置好的变量字符串。下面介绍4种替换模板方式:
1、使用内置
String message = ("您好%s,晚上好!您目前余额:%.2f元,积分:%d", "张三", 10.155, 10);
(message);
//您好张三,晚上好!您目前余额:10.16元,积分:10
2、使用内置MessageFormat
String message = ("您好{0},晚上好!您目前余额:{1,number,#.##}元,积分:{2}", "张三", 10.155, 10);
(message);
//您好张三,晚上好!您目前余额:10.16元,积分:10
3、使用自定义封装
。。。。。
private static Matcher m = ("\\$\\{\\w+\\}").matcher(template);
。。。。。public static String processTemplate(String template, Map<String, Object> params){
StringBuffer sb = new StringBuffer();
while (()) {
String param = ();
Object value = ((2, () - 1));
(sb, value==null ? "" : ());
}
(sb);
return ();
}
public static void main(String[] args){
Map map = new HashMap();
("name", "张三");
("money", ("%.2f", 10.155));
("point", 10);
message = processTemplate("您好${name},晚上好!您目前余额:${money}元,积分:${point}", map);
(message);
//您好张三,晚上好!您目前余额:10.16元,积分:10
}
4、使用模板引擎freemarker
首先引入,这里以2.3.23版本为例,如果使用maven的配置
<dependency>
<groupId></groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
try {
map = new HashMap();
("name", "张三");
("money", 10.155);
("point", 10);
Template template = new Template("strTpl", "您好${name},晚上好!您目前余额:${money?string(\"#.##\")}元,积分:${point}", new Configuration(new Version("2.3.23")));
StringWriter result = new StringWriter();
(map, result);
(());
//您好张三,晚上好!您目前余额:10.16元,积分:10
}catch(Exception e){
();
}
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
/**
* 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[]{"张三", ("%.2f", 10.155), 10};
(processFormat("您好%s,晚上好!您目前余额:%s元,积分:%d", obj));
(processMessage("您好{0},晚上好!您目前余额:{1}元,积分:{2}", obj));
Map map = new HashMap();
("name", "张三");
("money", ("%.2f", 10.155));
("point", 10);
(processTemplate("您好${name},晚上好!您目前余额:${money}元,积分:${point}", map));
(processFreemarker("您好${name},晚上好!您目前余额:${money}元,积分:${point}", map));
}
/**
* 渲染模板
* @param template 模版
* @param params 参数
* @return
*/
public static String processFormat(String template, Object... params) {
if (template == null || params == null)
return null;
return (template, params);
}
/**
* MessageFormat渲染模板
* @param template 模版
* @param params 参数
* @return
*/
public static String processMessage(String template, Object... params) {
if (template == null || params == null)
return null;
return (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 = ("\\$\\{\\w+\\}").matcher(template);
while (()) {
String param = ();
Object value = ((2, () - 1));
(sb, value == null ? "" : ());
}
(sb);
return ();
}
/**
* 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);
(params, result);
return ();
} catch (Exception e) {
return null;
}
}
}
综合,完整示例:
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
/**
* 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[]{"张三", ("%.2f", 10.155), 10};
(processFormat("您好%s,晚上好!您目前余额:%s元,积分:%d", obj));
(processMessage("您好{0},晚上好!您目前余额:{1}元,积分:{2}", obj));
Map map = new HashMap();
("name", "张三");
("money", ("%.2f", 10.155));
("point", 10);
(processTemplate("您好${name},晚上好!您目前余额:${money}元,积分:${point}", map));
(processFreemarker("您好${name},晚上好!您目前余额:${money}元,积分:${point}", map));
}
/**
* 渲染模板
* @param template 模版
* @param params 参数
* @return
*/
public static String processFormat(String template, Object... params) {
if (template == null || params == null)
return null;
return (template, params);
}
/**
* MessageFormat渲染模板
* @param template 模版
* @param params 参数
* @return
*/
public static String processMessage(String template, Object... params) {
if (template == null || params == null)
return null;
return (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 = ("\\$\\{\\w+\\}").matcher(template);
while (()) {
String param = ();
Object value = ((2, () - 1));
(sb, value == null ? "" : ());
}
(sb);
return ();
}
/**
* 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);
(params, result);
return ();
} catch (Exception e) {
return null;
}
}
}
/user/index/article/id/
/**
* 简单实现${}模板功能
* 如${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 = > 0 ? defaultNullReplaceVals[0] : "";
Pattern pattern = ("\\$\\{([^}]+)}");
StringBuffer newValue = new StringBuffer(());
Matcher matcher = (templateStr);
while (()) {
String key = (1);
String r = (key) != null ? (key).toString() : nullReplaceVal;
(newValue, ("\\\\", "\\\\\\\\")); //这个是为了替换windows下的文件目录在java里用\\表示
}
(newValue);
return ();
}
//测试方法
public static void main(String[] args) {
String tmpLine = "简历:\n 姓名: ${姓} ${名} \n 性别: ${性别}\n 年龄: ${年龄} \n";
Map<String, Object> data = new HashMap<String, Object>();
("姓", "wen");
("名", "66");
("性别", "man");
("年龄", "222");
(simpleTemplate(tmpLine, null, "--"));
}
/blog/830526
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 = (jsonStr, );
for (Object s : ()) {
template = ("\\$\\{".concat(()).concat("\\}")
, (()).toString());
}
return template;
}
public static void main(String[] args) throws IOException {
(generateWelcome(jsonStr,template));
}
/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 = ();
for(Entry<String, String> entry : sets) {
String regex = "\\$\\{" + () + "\\}";
Pattern pattern = (regex);
Matcher matcher = (content);
content = (());
}
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<>();
("name", "java");
("six", "6");
content = (content, map);
(content);
}
有两个变量需要替换,name和six,对应的值分别为java和6,同时name调用了两次。
结果:
hello java, 1 2 3 4 5 6 7, again java.
http:///javazheng-ze-biao-da-shi-shi-xian-name-xing-shi-de-zi-fu-chuan-mo-ban/