把resource拷贝到test目录下
只保留文件夹结构和test1.ftl这个模板文件就可以了。
新建一个包
编写测试类
使用freemaker提供的方法生成静态文件
Configuration是import freemarker.template.Configuration;包下的
手动的设置模板的路径。获取当前类的classPath然后拼上template的路径
抛出异常
获取test1.ftl这个模板
定义获取数据的方法。填充map的数据是从上节课的controller里面复制过来的。单独定义一个getMap的方法来获取。
静态化
processTemplateIntoString方法也要抛出异常。TemplateException
一步步往下走报错。
路径写错了 漏了一个s
复制静态化后的字符串内容。
粘贴到一个编辑器里面
package com.xuecheng.test.freemarker; import com.xuecheng.test.freemarker.model.Student; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import java.io.File; import java.io.IOException; import java.util.*; @SpringBootTest @RunWith(SpringRunner.class) public class FreemarkerTest { //测试静态化,基于ftl模板文件生成html文件 @Test public void testGenerateHtml() throws IOException, TemplateException { //定义配置类 Configuration configuration = new Configuration(Configuration.getVersion()); //定义模板 //得到classpath的路径 String classpath = this.getClass().getResource("/").getPath(); configuration.setDirectoryForTemplateLoading(new File(classpath+"/templates/")); //获取模板文件内容。 Template template = configuration.getTemplate("test1.ftl"); //定义数据模型。 Map map=getMap(); //静态化 String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map); System.out.println(content); } public Map getMap(){ Map<String,Object> map=new HashMap<>(); map.put("name","黑马程序员"); Student stu1 = new Student(); stu1.setName("小明"); stu1.setAge(18); stu1.setMoney(1000.86f); stu1.setBirthday(new Date()); Student stu2 = new Student(); stu2.setName("小红"); stu2.setMoney(200.1f); stu2.setAge(19); stu2.setBirthday(new Date()); List<Student> friends = new ArrayList<>(); friends.add(stu1); stu2.setFriends(friends); stu2.setBestFriend(stu1); List<Student> stus = new ArrayList<>(); stus.add(stu1); stus.add(stu2); //向数据模型放数据 map.put("stus",stus); //准备map数据 HashMap<String,Student> stuMap = new HashMap<>(); stuMap.put("stu1",stu1); stuMap.put("stu2",stu2); //向数据模型放数据 map.put("stu1",stu1); //向数据模型放数据 map.put("stuMap",stuMap); map.put("point",102920122); return map; } }