freeMarker入门实例就是最好的入门资料,如下即为入门的工程实例。
一.工程结构
二.代码
1.TemplateDemo.java
package com.bijian.study; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import org.w3c.dom.Document; import freemarker.ext.beans.BeansWrapper; import freemarker.template.Configuration; import freemarker.template.ObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateHashModel; import freemarker.template.TemplateModel; public class TemplateDemo { public static void main(String[] args) throws Exception { //---------------------FreeMarker配置 --------------------------- FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer(); //指定模板文件路径 //file:/D:/SoftWare/workspace/FreeMarkerDemo/bin/com/bijian/study/ //String templateLoaderPath = "file:" + TemplateDemo.class.getResource("").getPath(); //file:/D:/SoftWare/workspace/FreeMarkerDemo/bin/ //String templateLoaderPath = "file:" + TemplateDemo.class.getClassLoader().getResource("").getFile(); //file:D:\SoftWare\workspace\FreeMarkerDemo\. //String templateLoaderPath = "file:" + new File(".").getAbsolutePath(); //file:D:\SoftWare\workspace\FreeMarkerDemo String templateLoaderPath = "file:" + new File("").getAbsolutePath(); freeMarkerConfigurer.setTemplateLoaderPath(templateLoaderPath); Properties settings = new Properties(); settings.setProperty("template_update_delay", "0"); settings.setProperty("default_encoding", "UTF-8"); settings.setProperty("locale", "zh_CN"); settings.setProperty("classic_compatible", "true"); freeMarkerConfigurer.setFreemarkerSettings(settings); Configuration configuration = freeMarkerConfigurer.createConfiguration(); Template template = configuration.getTemplate("freeMarkerDemo.ftl"); //---------------------FreeMarker配置--------------------------- //==========================范例 start================================== Map<String, Object> parameters = new HashMap<String, Object>(); //1.简单字符串 parameters.put("textDemo", "Hello World!!"); //2.计算||条件判断||输出特殊字符 int a = 1; int b = 2; parameters.put("a", a); parameters.put("b", b); //3.遍历List List<String> list = new ArrayList<String>(); list.add("早餐"); list.add("中餐"); list.add("晚餐"); parameters.put("list", list); //4.遍历map Map<String, Object> map = new HashMap<String, Object>(); map.put("key1", "value1"); map.put("key2", "value2"); parameters.put("map", map); //5.遍历复杂map Map<String,Object> userInfo = new HashMap<String,Object>(); userInfo.put("username","username"); Map<String,Object> cMap = new HashMap<String,Object>(); cMap.put("cKey1", "cValue1"); cMap.put("cKey2", "cValue2"); userInfo.put("cMap",cMap); parameters.put("userinfo", userInfo); //6.遍历嵌套map Map<String, Object> outerMap = new HashMap<String, Object>(); Map<String, String> innerMap = new HashMap<String, String>(); innerMap.put("innerKey1", "innerValue1"); innerMap.put("innerKey2", "innerValue2"); outerMap.put("key1", "value1"); outerMap.put("key2", "value2"); outerMap.put("innerMap", innerMap); parameters.put("outerMap", outerMap); //7.Map、List嵌套 Map<String, Object> mMap = new HashMap<String, Object>(); List<String> innerList = new ArrayList<String>(); innerList.add("吃早餐"); innerList.add("吃中餐"); innerList.add("吃晚餐"); mMap.put("key1", "value1"); mMap.put("key2", "value2"); mMap.put("innerList", innerList); parameters.put("mMap", mMap); //8.调用对象方法 TemplateDemo tDemo = new TemplateDemo(); parameters.put("tDemo", tDemo); //9.XPath读取XML配置信息 List<UserDTO> users = getUsers(); parameters.put("users", users); //10.调用静态方法 BeansWrapper wrapper = BeansWrapper.getDefaultInstance(); TemplateHashModel staticModels = wrapper.getStaticModels(); TemplateModel staticT = staticModels.get(TemplateDemo.class.getName()); parameters.put("T", staticT); //11.枚举 TemplateHashModel enumModels = wrapper.getEnumModels(); TemplateHashModel enumDemo = (TemplateHashModel) enumModels.get(EnumDemo.class.getName()); parameters.put("E", enumDemo); //12.模板模型 ObjectWrapper objectWrapper = wrapper.getOuterIdentity(); TemplateModel userModel = objectWrapper.wrap(new UserDTO(){ { setName("testUser"); setId("12345678"); } }); parameters.put("userModel", userModel); //==========================范例 end================================== //-----------------------根据模板和参数生成字符串---------------------------- String ftl = FreeMarkerTemplateUtils.processTemplateIntoString(template, parameters); System.out.println(ftl); } public String getHello(String name) { return "Hello " + name; } public static List<UserDTO> getUsers() throws Exception { List<UserDTO> users = new ArrayList<UserDTO>(); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(new File(TemplateDemo.class.getResource("userInfo.xml").getPath())); XPath xpath = XPathFactory.newInstance().newXPath(); String userCount = (String) xpath.evaluate("count(.//Users/user)", document, XPathConstants.STRING); for (int i = 0, count = Integer.valueOf(userCount); i < count; i++) { String userId = (String) xpath.evaluate(".//Users/user[" + (i + 1) + "]/@id", document, XPathConstants.STRING); String name = (String) xpath.evaluate(".//Users/user[" + (i + 1) + "]/name", document, XPathConstants.STRING); UserDTO userDTO = new UserDTO(); userDTO.setId(userId); userDTO.setName(name); users.add(userDTO); } return users; } public static String staticMethod() { return "A STATIC method is executing"; } }
2.UserDTO.java
package com.bijian.study; public class UserDTO { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
3.EnumDemo.java
package com.bijian.study; public enum EnumDemo { Spring, Summer, Autumn, Winter; public String getSeason() { switch (this) { case Spring: return "春天"; case Summer: return "夏天"; case Autumn: return "秋天"; case Winter: return "冬天"; default: return "你想表达啥!!!"; } } }
4.userInfo.xml
<Users> <user id="user1"> <name>张三</name> </user> <user id="user2"> <name>李四</name> </user> <user id="user3"> <name>张二</name> </user> <user id="userx"> <name>王五</name> </user> </Users>
5.freeMarkerDemo.ftl
<#-- ==================FreeMarker模板生成的内容 START===================== --> 范例一:简单输出 textDemo的值是:${textDemo} 范例二:计算||条件判断||输出特殊字符 a == ${a};b == ${b} ${a} + ${b} = ${a + b} <#if (a > b)> a 大于 b <#elseif (a == b)> a 等于 b <#elseif (a < b)> a 小于 b </#if> <#assign c = a + b> <#noparse><#assign c = a + b>; ${c} = </#noparse>${c} ${r'<#assign c = a + b>'}; ${r'${c}'} = ${c} 范例三:List遍历 每天吃几餐: <#list list as item> ${item_index + 1}.${item} </#list> 范例四:Map遍历 <#list map?keys as key> ${key} == ${map[key]} </#list> 范例五:复杂Map遍历 <#assign cmap = userinfo.cMap> <#list cmap?keys as key> ${key} == ${cmap[key]} </#list> 范例六:Map嵌套遍历 <#list outerMap?keys as key> <#assign innerMap = outerMap[key]> <#if innerMap?is_hash> <#list innerMap?keys as _key> ${_key} == ${innerMap[_key]} </#list> <#elseif innerMap?string> ${key} == ${innerMap} <#-- ${key} == ${outerMap[key]} --> </#if> </#list> 范例七:Map、List嵌套遍历 <#list mMap?keys as key> <#assign list = mMap[key]> <#-- if key=="innerList" --> <#if key?ends_with("List")> <#list list as item> ${item_index + 1}.${item} </#list> <#else> ${key} == ${list} </#if> </#list> 范例八:调用对象方法 ${tDemo.getHello('FreeMarker')} 范例九:XPath读取XML配置信息 一共有:${users?size}个人,他们分别是: <#list users as user> ${user.id}:${user.name} </#list> <#assign firstPerson = users?first> 第一个人是:${firstPerson.name} <#assign lastPerson = users?last> 最后一个人是:${lastPerson.name} 范例十:调用静态方法 ${T.staticMethod()} 范例十一:枚举 ${E.Summer.getSeason()} ${E.Autumn.getSeason()} 范例十二:模板模型 ${userModel.name}:${userModel.getName()} ${userModel.id}:${userModel.getId()} <#-- ==================FreeMarker模板生成的内容 END===================== -->
三.TemplateDemo.java的主方法运行结果
范例一:简单输出 textDemo的值是:Hello World!! 范例二:计算||条件判断||输出特殊字符 a == 1;b == 2 1 + 2 = 3 a 小于 b <#assign c = a + b>; ${c} = 3 <#assign c = a + b>; ${c} = 3 范例三:List遍历 每天吃几餐: 1.早餐 2.中餐 3.晚餐 范例四:Map遍历 key2 == value2 key1 == value1 范例五:复杂Map遍历 cKey1 == cValue1 cKey2 == cValue2 范例六:Map嵌套遍历 key2 == value2 key1 == value1 innerKey1 == innerValue1 innerKey2 == innerValue2 范例七:Map、List嵌套遍历 1.吃早餐 2.吃中餐 3.吃晚餐 key2 == value2 key1 == value1 范例八:调用对象方法 Hello FreeMarker 范例九:XPath读取XML配置信息 一共有:4个人,他们分别是: user1:张三 user2:李四 user3:张二 userx:王五 第一个人是:张三 最后一个人是:王五 范例十:调用静态方法 A STATIC method is executing 范例十一:枚举 夏天 秋天 范例十二:模板模型 testUser:testUser 12345678:12345678