2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > Freemarker生成静态化文件

Freemarker生成静态化文件

时间:2020-11-09 11:36:05

相关推荐

Freemarker生成静态化文件

页面 test1.ftl

<!DOCTYPE html><html><head><meta charset="utf-8"><title>Hello World!</title></head><body>Hello ${name}!<br/><table><tr><td>序号</td><td>姓名</td><td>年龄</td><td>钱包</td></tr><#list stus as stu><tr><td>${stu_index + 1}</td><td <#if stu.name =='小明'>style="background:red;"</#if>>${stu.name}</td><td>${stu.age}</td><td >${stu.mondy}</td></tr></#list></table><br/><br/>输出stu1的学生信息:<br/>姓名:${stuMap['stu1'].name}<br/>年龄:${stuMap['stu1'].age}<br/>输出stu1的学生信息:<br/>姓名:${stu1.name}<br/>年龄:${stu1.age}<br/>遍历输出两个学生信息:<br/><table><tr><td>序号</td><td>姓名</td><td>年龄</td><td>钱包</td></tr><#list stuMap?keys as k><tr><td>${k_index + 1}</td><td>${stuMap[k].name}</td><td>${stuMap[k].age}</td><td >${stuMap[k].mondy}</td></tr></#list></table></br><table><tr><td>姓名</td><td>年龄</td><td>出生日期</td><td>钱包</td><td>最好的朋友</td><td>朋友个数</td><td>朋友列表</td></tr><#if stus??><#list stus as stu><tr><td>${stu.name!''}</td><td>${stu.age}</td><td>${(stu.birthday?date)!''}</td><td>${stu.mondy}</td><td>${(stu.bestFriend.name)!''}</td><td>${(stu.friends?size)!0}</td><td><#if stu.friends??><#list stu.friends as firend>${firend.name!''}<br/></#list></#if></td></tr></#list></#if></table><br/><#assign text="{'bank':'工商银行','account':'101019212'}" /><#assign data=text?eval />开户行:${data.bank} 账号:${data.account}</body></html>

代码:

package com.xuecheng.test.freemarker;import com.xuecheng.test.freemarker.model.Student;import freemarker.cache.StringTemplateLoader;import freemarker.template.Configuration;import freemarker.template.Template;import freemarker.template.TemplateException;import mons.io.IOUtils;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.*;import java.util.*;/*** @author Administrator* @version 1.0* @create -06-13 10:07**/@SpringBootTest@RunWith(SpringRunner.class)public class FreemarkerTest {//基于模板生成静态化文件@Testpublic void testGenerateHtml() throws IOException, TemplateException {//创建配置类Configuration configuration=new Configuration(Configuration.getVersion());String classpath = this.getClass().getResource("/").getPath();//设置模板路径configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));//设置字符集configuration.setDefaultEncoding("utf-8");//加载模板Template template = configuration.getTemplate("test1.ftl");//数据模型Map map = getMap();//静态化String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);//静态化内容System.out.println(content);InputStream inputStream = IOUtils.toInputStream(content);//输出文件FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test1.html"));int copy = IOUtils.copy(inputStream, fileOutputStream);}//基于模板字符串生成静态化文件@Testpublic void testGenerateHtmlByString() throws IOException, TemplateException {//创建配置类Configuration configuration=new Configuration(Configuration.getVersion());//获取模板内容//模板内容,这里测试时使用简单的字符串作为模板String templateString="" +"<html>\n" +" <head></head>\n" +" <body>\n" +" 名称:${name}\n" +" </body>\n" +"</html>";//加载模板//模板加载器StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();stringTemplateLoader.putTemplate("template",templateString);configuration.setTemplateLoader(stringTemplateLoader);Template template = configuration.getTemplate("template","utf-8");//数据模型Map map = getMap();//静态化String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);//静态化内容System.out.println(content);InputStream inputStream = IOUtils.toInputStream(content);//输出文件FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test1.html"));IOUtils.copy(inputStream, fileOutputStream);}//数据模型private Map getMap(){Map<String, Object> map = new HashMap<>();//向数据模型放数据map.put("name","黑马程序员");Student stu1 = new Student();stu1.setName("小明");stu1.setAge(18);stu1.setMondy(1000.86f);stu1.setBirthday(new Date());Student stu2 = new Student();stu2.setName("小红");stu2.setMondy(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);return map;}}

抽取成方法:

调用getPageHtml 方法得当静态化数据

//页面静态化方法/*** 静态化程序获取页面的DataUrl** 静态化程序远程请求DataUrl获取数据模型。** 静态化程序获取页面的模板信息** 执行页面静态化*/public String getPageHtml(String pageId){//获取数据模型Map model = getModelByPageId(pageId);if(model == null){//数据模型获取不到ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_DATAISNULL);}//获取页面的模板信息String template = getTemplateByPageId(pageId);if(StringUtils.isEmpty(template)){ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_TEMPLATEISNULL);}//执行静态化String html = generateHtml(template, model);return html;}//执行静态化private String generateHtml(String templateContent,Map model ){//创建配置对象Configuration configuration = new Configuration(Configuration.getVersion());//创建模板加载器StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();stringTemplateLoader.putTemplate("template",templateContent);//向configuration配置模板加载器configuration.setTemplateLoader(stringTemplateLoader);//获取模板try {Template template = configuration.getTemplate("template");//调用api进行静态化String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);return content;} catch (Exception e) {e.printStackTrace();}return null;}//获取页面的模板信息private String getTemplateByPageId(String pageId){//取出页面的信息CmsPage cmsPage = this.getById(pageId);if(cmsPage == null){//页面不存在ExceptionCast.cast(CmsCode.CMS_PAGE_NOTEXISTS);}//获取页面的模板idString templateId = cmsPage.getTemplateId();if(StringUtils.isEmpty(templateId)){ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_TEMPLATEISNULL);}//查询模板信息Optional<CmsTemplate> optional = cmsTemplateRepository.findById(templateId);if(optional.isPresent()){CmsTemplate cmsTemplate = optional.get();//获取模板文件idString templateFileId = cmsTemplate.getTemplateFileId();//从GridFS中取模板文件内容//根据文件id查询文件GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(templateFileId)));//打开一个下载流对象GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());//创建GridFsResource对象,获取流GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);//从流中取数据try {String content = IOUtils.toString(gridFsResource.getInputStream(), "utf-8");return content;} catch (IOException e) {e.printStackTrace();}}return null;}//获取数据模型private Map getModelByPageId(String pageId){//取出页面的信息CmsPage cmsPage = this.getById(pageId);if(cmsPage == null){//页面不存在ExceptionCast.cast(CmsCode.CMS_PAGE_NOTEXISTS);}//取出页面的dataUrlString dataUrl = cmsPage.getDataUrl();if(StringUtils.isEmpty(dataUrl)){//页面dataUrl为空ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_DATAURLISNULL);}//通过restTemplate请求dataUrl获取数据ResponseEntity<Map> forEntity = restTemplate.getForEntity(dataUrl, Map.class);Map body = forEntity.getBody();return body;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。