背景
有时需要定义一些模板,然后用实际值替换占位符. 这里介绍一个jar包 ST4.
还是以生成验证码短信的例子为背景.
如下是我定义的模板,需要传入用户名和验证码.
1 2
| 你好 <name> , 你的验证码是 <captcha> 验证码5分钟有效,尽快使用
|
最终生成的文本如下
1 2
| 你好 张三 , 你的验证码是 123456 验证码5分钟有效,尽快使用
|
如果模板越复杂使用ST4越能感觉到优势, 如用于生成源代码、web页面、电子邮件等复杂样式的文本.
github地址
https://github.com/antlr/stringtemplate4
使用示例
pom.xml 引入依赖
1 2 3 4 5
| <dependency> <groupId>org.antlr</groupId> <artifactId>ST4</artifactId> <version>4.0.8</version> </dependency>
|
一些示例
示例1 简单示例
1 2 3 4 5 6 7 8 9
|
@Test public void helloWorld(){ ST hello = new ST("Hello, <name>"); hello.add("name", "World"); System.out.println(hello.render()); }
|
这个例子算是st4的helloworld版,让你快速感受下.
示例2 STGroupFile的使用
1 2 3 4 5 6 7 8 9 10 11 12 13
|
@Test public void testGroupFile(){ STGroup group=new STGroupFile("templates/templates.stg"); ST st=group.getInstanceOf("ShortMessage"); st.add("name","张三"); st.add("captcha","123456"); String result=st.render(); System.out.println(result); }
|
如下定义模板文件, 可以看到其定义有点像函数的形式.
resouces/templates/templates.stg
1 2 3 4 5
| ShortMessage(name,captcha) ::= << 你好 <name> , 你的验证码是 <captcha> 验证码5分钟有效,尽快使用 >>
|
当模板过于复杂时,以硬编码的方式将模板写在代码中不方便,因此将模板内容写入到文件是一个不错的选择.
示例3 传入参数是对象
1 2 3 4 5 6 7 8 9 10 11
|
@Test public void testModelObject(){ ST st = new ST("<b>$u.id$</b>: $u.name$", '$', '$'); st.add("u", new User(999, "parrt")); String result = st.render(); System.out.println(result); }
|
这个例子也很经典
- 一是其传入的参数是一个对象,而不是字符串等基本类型了
- 二是这里自己指定了占位符