背景:
工程框架里的短信功能,有個模版配置,模版配置里會根據(jù)客戶信息設(shè)置相應(yīng)的參數(shù),源框架別人開發(fā)用的是正則表達(dá)式加String.replace(),實(shí)在太不靈活,太low。
能力有限,只有下面這個笨拙的方法(有大牛經(jīng)過,望止步指點(diǎn)一二)
工具
- Freemarker 2.3.0
- Eclipse(JDK1.7)
下面直接貼代碼,大家覺得有用,直接搬磚,有更好的改造,希望可以共享,支持開源精神。
FreemarkerTest.java
import java.io.IOException;
import java.io.StringWriter;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.utility.NullArgumentException;
public class FreemarkerTest {
private static String REPLACEERROR = "替換失敗,請檢查參數(shù)是否有誤" ;
private static Configuration cfg;
private static StringTemplateLoader stl;
static {
cfg = new Configuration(Configuration.VERSION_2_3_0);
stl = new StringTemplateLoader();
}
/**
* 單個模版,單個對象屬性替換
*
* @throws NullArgumentException
*
* @param tempname 模版名稱,唯一標(biāo)示
* @param stringtemp 模版字符串
* @param object 模版屬性的類對象
* @return 替換后生成的字符串
*/
public static String stringTemplateReplaceForObject(String tempname, String stringtemp, Object object) {
if (stringtemp == null || stringtemp.length() <= 0) {
throw new NullArgumentException("替換模版為空,不允許!");
}
if (object == null) {
throw new NullArgumentException("替換對象不要傳空!");
}
try {
stl.putTemplate(tempname, stringtemp);
cfg.setTemplateLoader(stl);
Template template = cfg.getTemplate(tempname);
StringWriter writer = new StringWriter() ;
template.process(object, writer);
return writer.toString();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return REPLACEERROR;
}
/**
* 模版二次替換,需與stringTemplateReplaceForObject(xxx,xxx,xxx)方法結(jié)合使用,不然會出現(xiàn)不存在指定的模版異常
*
* @see #stringTemplateReplaceForObject(String, String, Object)
*
* @param tempname 模版名稱
* @param object 替換的對象
* @return 替換后生成的字符串
*/
public static String stringTempReplaceToTempNameForObject(String tempname, Object object) {
try {
Template template = cfg.getTemplate(tempname);
StringWriter writer = new StringWriter() ; // StringWriter會緩存,不能設(shè)置為全局
template.process(object, writer);
return writer.toString();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
return REPLACEERROR;
}
}
測試
public static void main(String[] args) throws Exception{
Person person = new Person() ;
person.setName("替換成張三");
String s = FreemarkerTest.stringTemplateReplaceForObject("person", "hello:${name}", person);
System.out.println(s);
Student student = new Student();
student.setAge(25);
Map<String,Object> map = new HashMap<>() ;
map.put("person", person);
map.put("student", student);
s = FreemarkerTest.stringTemplateReplaceForObject("student", "人的名字是:${person.name},學(xué)生年齡:${student.age}", map);
System.out.println(s);
person.setName("把名字換成李四");
s= FreemarkerTest.stringTempReplaceToTempNameForObject("person",person);
System.out.println(s);
}