使用freemarker,動態填充字符串模板

1.引入需要的jar包:

<!-- 引入Freemarker的依賴 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>

2.example

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
 
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
 
public class StrTemplate {
	public static void main(String[] args) throws IOException, TemplateException{
		String StrTemplate = "姓名:${name};年齡:${age}"; // 測試模板數據(一般存儲在數據庫中)
		Map<String,Object> map = new HashMap<String,Object>();  // map,需要動態填充的數據
		map.put("name", "張三");
		map.put("age", "25");
		String resultStr = process(StrTemplate, map, null); // 解析字符串模板的方法,並返回處理後的字符串
		System.out.println(resultStr);
	}
	/**
	 * 解析字符串模板,通用方法
	 * 
	 * @param template
	 *            字符串模板
	 * @param model; 
	 *            數據
	 * @param configuration
	 *            配置
	 * @return 解析後內容
	 */
	public static String process(String template, Map<String, ?> model, Configuration configuration) 
			throws IOException, TemplateException {
		if (template == null) {
			return null;
		}
		if (configuration == null) {
			configuration = new Configuration();
		}
		StringWriter out = new StringWriter();
		new Template("template", new StringReader(template), configuration).process(model, out);
		return out.toString();
	}
}

3.輸出結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章