1、FreeMarker简介
FreeMarker是一个用Java语言编写的模板引擎,它基于模板来生成文本输出。FreeMarker与Web容器无关,即在Web运行时,它并不知道Servlet或HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成XML,JSP或Java 等。
FreeMarker可应用于的动态页面的静态化,比如网站首页的静态化或者包含HTML页面的邮件。
2、FreeMarker常用标签
Java通过传入一个Map变量,FreeMarker标签再读取Map中的值
2.1 变量
变量variable:${name}
如果Map中有键值对{"name": "老马"}
那么就会输出:
变量variable:老马
2.2 if语句
判断If String: <#if name == "马云">马云
<#elseif name == "马化腾"> 马化腾
<#else> name is not 马云 or 马化腾
</#if>
<!-- (age>17) 也可改成age > 17-->
判断If int: <#if (age>17)>age is larger then 17
<#elseif age < 17> age smaller than 17
<#else>age is equal with 17
</#if>
2.3 遍历List
遍历List: <#list names as name>
${name}
</#list>
2.4 Map
读取Map中的值: ${map.name1},${map["name1"]}
遍历 Map keys: <#list map?keys as nameKey>
${nameKey}:${map[nameKey]}
</#list>
遍历 Map values: <#list map?values as value>
${value}
</#list>
2.5 Object
Object: ${user.name} ${user.age}
3、FreeMarker例子
3.1 模板文件test.ftl
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>FreeMarker Example</title>
</head>
<body>
变量variable:${name}
判断If String: <#if name == "马云">马云
<#elseif name == "马化腾"> 马化腾
<#else> name is not 马云 or 马化腾
</#if>
<!-- (age>17) 也可改成age > 17-->
判断If int: <#if (age>17)>age is larger then 17
<#elseif age < 17> age smaller than 17
<#else>age is equal with 17
</#if>
遍历List: <#list names as name>
${name}
</#list>
读取Map中的值: ${map.name1},${map["name1"]}
遍历 Map keys: <#list map?keys as nameKey>
${nameKey}:${map[nameKey]}
</#list>
遍历 Map values: <#list map?values as value>
${value}
</#list>
Object: ${user.name} ${user.age}
</body>
</html>
3.2 Java文件
package com.freemarker;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
public class Freemaker {
public static void main(String[] args) {
new Freemaker().testFreeMaker();
}
public void testFreeMaker() {
// 加载模板
String dir = "E:\\workspace\\freemarker\\templates";
Configuration config = new Configuration();
try {
config.setDirectoryForTemplateLoading(new File(dir));
// 设置对象包装器
config.setObjectWrapper(new DefaultObjectWrapper());
config.setLocale(Locale.CHINA);
config.setEncoding(Locale.CHINA, "UTF-8");
// 设置异常处理器
config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
List<String> names = new ArrayList<String>();
names.add("马云");
names.add("马化腾");
names.add("马尉华");
Map<String, Object> map = new HashMap<String, Object>();
map.put("name1", "马云");
map.put("name2", "马化腾");
map.put("name3", "马尉华");
// 定义数据模型
Map<String, Object> root = new HashMap<String, Object>();
root.put("name", "马尉华");
root.put("age", 18);
root.put("names", names);
root.put("map", map);
root.put("user", new User("王健林", 62));
// 通过freemaker解释模板,首先需要获得模板对象
Template temp = config.getTemplate("test.ftl");
// 定义模板输出到HTML文件
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("E:\\workspace\\freemarker\\templates\\test.html")));
// 模板解释
temp.process(root, out);
//输出到字符串
StringWriter writer = new StringWriter();;
temp.process(root, writer);
System.out.println(writer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.3 程序运行结果
<html>
<head>
<title>FreeMarker Example</title>
</head>
<body>
变量variable:马尉华
判断If String: name is not 马云 or 马化腾
<!-- (age>17) 也可改成age > 17-->
判断If int: age is larger then 17
遍历List: 马云,马化腾,马尉华,
读取Map中的值: name1=马云
遍历 Map keys: name3:马尉华,name1:马云,name2:马化腾,
遍历 Map values: 马尉华,马云,马化腾,
Object: 王健林 62
</body>
</html>
4、FreeMarker整合Spring
4.1 Spring配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
default-lazy-init="true">
<mvc:annotation-driven/>
<context:component-scan base-package="com.controller"/>
<mvc:default-servlet-handler/>
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPaths" value="/templates/" />
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0</prop>
<prop key="default_encoding">UTF-8</prop>
<prop key="locale">zh_CN</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="time_format">HH:mm:ss</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
</props>
</property>
</bean>
</beans>
4.2 Spring Controller
package com.controller;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import com.freemarker.User;
import freemarker.template.Template;
import freemarker.template.TemplateException;
@Controller
@RequestMapping("/freemarkerController")
public class FreemarkerController {
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@RequestMapping("/freemarker.do")
public String getFreeMarkerString(HttpServletRequest request, HttpServletResponse response){
String realPath=request.getSession().getServletContext().getRealPath("/");//获取web项目的路径
// String path=this.getClass().getResource("/").getPath();//获取类的当前目录
Template t = null;
try {
t = freeMarkerConfigurer.getConfiguration().getTemplate("test.ftl");
} catch (IOException e1) {
e1.printStackTrace();
}
List<String> names = new ArrayList<String>();
names.add("马云");
names.add("马化腾");
names.add("马尉华");
Map<String, Object> map = new HashMap<String, Object>();
map.put("name1", "马云");
map.put("name2", "马化腾");
map.put("name3", "马尉华");
// 定义数据模型
Map<String, Object> root = new HashMap<String, Object>();
root.put("name", "马尉华");
root.put("age", 18);
root.put("names", names);
root.put("map", map);
root.put("user", new User("王健林", 62));
String result = null;
try {
result = FreeMarkerTemplateUtils.processTemplateIntoString(t, root);
System.out.println(result);
String filePath = realPath + "\\templates\\test.html";
File file = new File(filePath);
if(!file.exists()){
file.createNewFile();
}
// 定义模板输出到HTML文件
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath),"UTF-8"));
t.process(root,out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
return "/templates/test.html";
}
}
4.3 程序运行结果
4.4 程序下载地址