springboot2.0结合freemarker生成静态化页面

Easter79
• 阅读 511

[TOC]

使用freemarker将页面生成html文件,本节测试html文件生成的方法:

1、使用模板文件静态化 定义模板文件,使用freemarker静态化程序生成html文件。 2、使用模板字符串静态化 定义模板字符串,使用freemarker静态化程序生成html文件。

1. pom.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2. application.yml配置

server:
  port: 8088
spring:
  application:
    name: test-freemarker
  #    freemarker配置
  freemarker:
    cache: false  #关闭模板缓存,方便测试
    settings:
      template_update_delay: 0  #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试
    template-loader-path: classpath:/templates
    charset: UTF-8
    check-template-location: true
    suffix: .ftl
    content-type: text/html
    expose-request-attributes: true
    expose-session-attributes: true
    request-context-attribute: request

3. 使用模板文件静态化

3.1 创建测试类,编写测试方法

package com.example.demo;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author john
 * @date 2019/12/20 - 19:09
 */
@SpringBootTest
public class TestFreemarkerHtml {
    //基于模板生成静态化文件
    @Test
    public 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<String, Object> map = new HashMap<>();
        map.put("name", "john");
        //静态化
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        //静态化内容
        System.out.println(content);
        InputStream inputStream = IOUtils.toInputStream(content);
        //输出文件
        FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test/test1.html"));
        int copy = IOUtils.copy(inputStream, fileOutputStream);
    }
}

编写模板

<html>
<head>
    <title>hello world!</title>
</head>
<body>
${name}<br/>
<#assign text="{'bank':'工商银行','account':'10101920201920212'}" />
<#assign data=text?eval />
开户行:${data.bank} 账号:${data.account}
</body>
</html>

springboot2.0结合freemarker生成静态化页面

生成文件

springboot2.0结合freemarker生成静态化页面

3.2 使用模板字符串静态化

package com.example.demo;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author john
 * @date 2019/12/20 - 19:09
 */
@SpringBootTest
public class TestFreemarkerHtml {
    //基于模板字符串生成静态化文件
    @Test
    public 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<String, Object> map = new HashMap<>();
        map.put("name", "john");
        //静态化
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        //静态化内容
        System.out.println(content);
        InputStream inputStream = IOUtils.toInputStream(content);
        //输出文件
        FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test/test2.html"));
        IOUtils.copy(inputStream, fileOutputStream);
    }
}

springboot2.0结合freemarker生成静态化页面

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Stella981 Stella981
2年前
SpringBoot获取Freemarker模板引擎,生成HTML代码
今天用Ajax异步添加评论,加载Freemarker模板引擎,生成模板模块1.新建Freemarker模板<liid"${comment.oId}"<div<divclass"avatartooltippedtooltippedn"ariala
Wesley13 Wesley13
2年前
Java 复杂excel报表导出
MyExcel,是一个可直接使用Html文件,或者使用内置的Freemarker、Groovy、Beetl等模板引擎Excel构建器生成的Html文件,以Html文件中的Table作为Excel模板来生成任意复杂布局的Excel的工具包,支持.xls、.xlsx格式,支持对背景色、边框、字体等进行个性化设置,支持合并单元格。Github:https:/
Wesley13 Wesley13
2年前
vscode定制Vue代码片段
文件首选项用户代码片段prefix:生成模板代码的快捷键scope:只有在html页面中使用这个快捷键才能生成模板description:快捷键描述{"vuehtm":{"scope":"html","prefix":"vuehtml",
Stella981 Stella981
2年前
PHP 生成静态文件html,php静态化
第一种:如果你愿意花费时间写一套模板解析方法的话,那么可以直接读取模板,然后将模板里的标签解析掉,再写入。    具体代码略……第二种:使用ob缓冲区例子:ob_end_clean();ob_start();$thisdisplay('article');//框架中显示页面的方法
Easter79 Easter79
2年前
Thymeleaf实用实例
1\.简介之前一直使用Freemarker,对Thymeleaf了解但是不熟悉,最近因为其他项目组他们要快速搭建后台,使用了一个三方的框架用到了Thymeleaf,所以进一步了解了一些。发现Thymeleaf更加像前端的模板语言,所以对静态页面有更好的兼容性,就是,如果是Freemarker模板文件,浏览器是解析不了的,会直接出错。而
Stella981 Stella981
2年前
Freemark(一): 简介及其使用
1\.Freemark简介FreeMarker是一款模板引擎:一种基于魔板的、用来生成输出文本的通用工具。类似模板引擎还有Velocity,CommonTemplate等。对于javaweb开发来说,使用FreeMarker模板,可以将java代码从页面中分离出来。开发人员只需关注业务逻辑代码,而由页面设计人员去设
Easter79 Easter79
2年前
SpringBoot获取Freemarker模板引擎,生成HTML代码
今天用Ajax异步添加评论,加载Freemarker模板引擎,生成模板模块1.新建Freemarker模板<liid"${comment.oId}"<div<divclass"avatartooltippedtooltippedn"ariala
Stella981 Stella981
2年前
Codeigniter 生成静态页面
使用CI来生成静态页面,其实很简单,就像论坛里面说的那样,读出页面中的数据,再写入html文件中,最后显示这个html文件就行了,好吧,上码。<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');            class
Wesley13 Wesley13
2年前
PHP 中 9 大缓存技术总结
1、全页面静态化缓存也就是将页面全部生成html静态页面,用户访问时直接访问的静态页面,而不会去走php服务器解析的流程。此种方式,在CMS系统中比较常见,比如dedecms;一种比较常用的实现方式是用输出缓存:Ob_start()要运行的代码$contentOb_
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k