前置工作參考:?Freemarker:基本使用_moreCalm的博客-CSDN博客
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-634131.html
1、修改application.yml配置文件
server:
port: 8881 #服務(wù)端口
spring:
application:
name: freemarker-demo #指定服務(wù)名
freemarker:
cache: false #關(guān)閉模板緩存,方便測(cè)試
settings:
template_update_delay: 0 #檢查模板更新延遲時(shí)間,設(shè)置為0表示立即檢查,如果時(shí)間大于0會(huì)有緩存不方便進(jìn)行模板測(cè)試
suffix: .ftl #指定Freemarker模板文件的后綴名
template-loader-path: classpath:/templates #模板存放位置
2、在test下創(chuàng)建測(cè)試類?FreemarkerTest
package com.heima;
import com.heima.entity.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.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
@SpringBootTest(classes = FreemarkerDemoApplication.class)
@RunWith(SpringRunner.class)
public class FreemarkerTest {
@Autowired
private Configuration configuration;
@Test
public void test() throws IOException, TemplateException {
//freemarker的模板對(duì)象,獲取模板
Template template = configuration.getTemplate("01-basic.ftl");
Map params = getData();
//合成
//第一個(gè)參數(shù) 數(shù)據(jù)模型
//第二個(gè)參數(shù) 輸出流
template.process(params, new FileWriter("E:/javaEE/heima-leadnews/heima-leadnews-test/freemarker-demo/src/main/resources/templates/test.html"));
}
private Map getData() {
Map<String, Object> map = new HashMap<>();
//小強(qiáng)對(duì)象模型數(shù)據(jù)
Student stu1 = new Student();
stu1.setName("小強(qiáng)");
stu1.setAge(18);
stu1.setMoney(1000.86f);
stu1.setBirthday(new Date());
//小紅對(duì)象模型數(shù)據(jù)
Student stu2 = new Student();
stu2.setName("小紅");
stu2.setMoney(200.1f);
stu2.setAge(19);
//將兩個(gè)對(duì)象模型數(shù)據(jù)存放到List集合中
List<Student> stus = new ArrayList<>();
stus.add(stu1);
stus.add(stu2);
//向map中存放List集合數(shù)據(jù)
map.put("stus", stus);
//創(chuàng)建Map數(shù)據(jù)
HashMap<String, Student> stuMap = new HashMap<>();
stuMap.put("stu1", stu1);
stuMap.put("stu2", stu2);
//向map中存放Map數(shù)據(jù)
map.put("stuMap", stuMap);
//返回Map
return map;
}
}
3、查看結(jié)果
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-634131.html
?
到了這里,關(guān)于Freemarker:生成HTML文本文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!