spring解析占位符小工具 & 模板引擎生成文本

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());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值