1.pom文件导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.application.yml加入配置
spring:
application:
name: test-freemarker #指定服务名
freemarker:
cache: false #关闭模板缓存,方便测试
settings:
template_update_delay: 0 #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试
3. 在resources下新建包templates,创建模板文件test.ftl
(FTL (代表FreeMarker模板语言))
ftl文件整体结构
-
文本:文本会照着原样来输出。
-
插值:这部分的输出会被计算的值来替换。插值由 ${ and } 所分隔(或者 #{ and },这种风格已经不建议再使用了)。
-
FTL 标签:FTL标签和HTML标签很相似,但是它们却是给FreeMarker的指示, 而且不会打印在输出内容中。
-
注释:注释和HTML的注释也很相似,但它们是由 <#-- 和 -->来分隔的。注释会被FreeMarker直接忽略, 更不会在输出内容中显示
<html>[文本]
<head>[文本]
<title>Welcome!</title>[文本]
</head>[文本]
<body>[文本]
<#-- Greet the user with his/her name -->[注释]
<h1>Welcome ${user}!</h1>[插值]
<p>We have these animals:[文本]
<ul>[文本]
<#list animals as animal>[FTL 标签]
<li>${animal.name} for ${animal.price} Euros[插值]
</#list>[FTL 标签]
</ul>[文本]
</body>[文本]
</html>
注意ftl文件区分大小写
4.1 在MVC层整合数据和模板
@RequestMapping("/freemarker")
@Controller
public class FreemarkerController {
@RequestMapping("/test1")
public String freemarker(Map<String, Object> map){
ArrayList<Student> students = new ArrayList<>();
Student stu1 = new Student("张大炮",10, new Date(), 1000F, null, null);
Student stu2 = new Student("张小炮",1, new Date(), 999F, null, null);
students.add(stu1);
students.add(stu2);
map.put("stus",students);
HashMap<String, Student> myMap = new HashMap<>();
myMap.put("stu1",stu1);
myMap.put("stu2",stu2);
map.put("myMap",myMap); //在ftl文件中通过${myMap}即可或得map中的数据
return "test1";
}
}
4.2 手动整合模板和数据
创建 Configuration 实例,模板加载器,生成html文件
首先你创建一个freemarker.template.Configuration实例,然后调整设置.Configuration实例是存储Freemarker的部分.同时它也负责创建Template对象(存储模板)
//freemarker制作html
public String generateHtml (String template, Map model) {
try {
//生成配置类
Configuration configuration = new Configuration(Configuration.getVersion());
//模板加载器
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
stringTemplateLoader.putTemplate("template", template); //template是 读ftl文件转成字符串格式
//配置模板加载器
configuration.setTemplateLoader(stringTemplateLoader);
//获取模板
Template template1 = configuration.getTemplate("template");
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template1, model); //model是一个map,存储着和template对应的数据
return html;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
方法2
import freemarker.template.*;
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
/* ------------------------------------------------------------------------ */
/* You should do this ONLY ONCE in the whole application life-cycle: */
/* Create and adjust the configuration singleton */
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates")); //template所在的文件目录
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW);
/* ------------------------------------------------------------------------ */
/* You usually do these for MULTIPLE TIMES in the application life-cycle: */
/* Create a data-model */
Map root = new HashMap();
root.put("user", "Big Joe");
Map latest = new HashMap();
root.put("latestProduct", latest);
latest.put("url", "products/greenmouse.html");
latest.put("name", "green mouse");
/* Get the template (uses cache internally) */
Template temp = cfg.getTemplate("test.ftl"); //这里是文件目录下的ftl文件名
/* Merge data-model with template */
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
// Note: Depending on what `out` is, you may need to call `out.close()`.
// This is usually the case for file output, but not for servlet output.
}
}