spring的占位符替换工具
很多字符串可以考虑使用模板引擎解析,比如freemarker或者thymeleaf,也可以使用正则表达式的替换去实现。但是一些比较简单的模板字符串使用MessageFormat感觉不够方便,所以使用spring的这个工具比较好
PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${", "}");
Properties properties = new Properties();
properties.setProperty("name", "zzhua");
// 输出:hello,zzhua,${sex}
// 没有找到值的,会原样输出
String result = helper.replacePlaceholders("hello,${name},${sex}", properties);
System.out.println(result);
String key = "U72BZ-YY7WW-LTPRY-RIQBS-QROX3-3LBQT";
HashMap<String, Object> map = new HashMap<>();
map.put("key", key);
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://apis.map.qq.com/ws/district/v1/list?key={key}", String.class, map);
System.out.println(responseEntity);
freemarker模板
依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
模板
<html>
<head></head>
<body>
欢迎注册!<img src="cid:pic"/> 您的验证码为: ${code}, 有效时间为5分钟
</body>
</html>
测试
public static void main(String[] args) throws IOException, TemplateException {
Configuration configuration = new Configuration();
SpringTemplateLoader springTemplateLoader = new SpringTemplateLoader(new DefaultResourceLoader(), "classpath:/templates");
configuration.setTemplateLoader(springTemplateLoader);
// FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(new File("d:/Projects/boot-blog/src/main/resources/templates/"));
// configuration.setTemplateLoader(fileTemplateLoader);
Template template = configuration.getTemplate("registerTpl.ftl");
HashMap<String, Object> data = new HashMap<>();
data.put("code", "123");
StringWriter stringWriter = new StringWriter();
template.process(data, stringWriter);
stringWriter.flush();
System.out.println(stringWriter.toString());
}

被折叠的 条评论
为什么被折叠?



