FreeMark创建静态页使用小结

本文介绍如何在SpringBoot项目中使用FreeMarker生成静态HTML页面,包括配置、代码实现及模板示例,适用于快速部署和优化网站性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FreeMarker页面静态化使用小结

1.前置准备(此处为SpringBoot项目)

(1)依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>

(2)配置文件[无参考意义,具体配置需结合实际]

## freemarker模板
spring.freemarker.template-loader-path=classpath:/templates/,file:D:\\WorkSpace\\xxx\\src\\main\\webapp\\WEB-INF\\views\\
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl
spring.freemarker.settings.template_exception_handler=ignore

2.生成页面代码

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Map;
import java.util.Properties;

@Service
public class FreemarkerService  {

    private static final Configuration cfg;

    static {
        //设置版本
        cfg = new Configuration(Configuration.VERSION_2_3_28);

        //加载配置文件
        Properties properties = new Properties();
        InputStream inputStream = FreemarkerService.class.getResourceAsStream("/application.properties");
        InputStreamReader inputStreamReader = null;

        try {
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            properties.load(inputStreamReader);
            //获取模板存放路径
            String templatePath = properties.getProperty("spring.freemarker.template-loader-path");
            String[] split = templatePath.split(",");
            templatePath = split[1].replace("file:", "");

            // 设置模板路径(此处读取的配置文件方式可能不通用,可根据实际需要调整)
            cfg.setDirectoryForTemplateLoading(new File(templatePath));
            // 设置默认编码
            cfg.setDefaultEncoding("utf-8");
            //若发生错误,HTML_DEBUG_HANDLER会生成错误信息到生成页面
            //若发生错误,RETHROW_HANDLER错误信息会输出到控制台
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param modeName       模板名称
     * @param folder         生成后的文件目录
     * @param targetFileName 生成后的HTML名称
     * @param params         传入模板的参数
     * @Author: cx
     * @Date: 15:57 2019/12/4
     * @Description:生成静态页面
     */
    public static void createHtml(String modeName, String targetFileName, String folder, Map<String, Object> params) throws Exception {
        Writer out = null;
        //找到服务器缓存目录,可以自己指定目录
//        String folder = System.getProperty("java.io.tmpdir");
        //创建目录
        File fileDir = new File(folder);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        //通过匹配路径格式拼接完整生成路径
        String outFile = folder + File.separator + targetFileName;
        try {
            File file = new File(outFile);
            //生成空HTML文件
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();

            // 创建模版对象
            Template template = cfg.getTemplate(modeName);

            // 设置输出流(设置编码 UTF-8)
            out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");

            // 模版数据插入参数,通过输出流插入到HTML中
            template.process(params, out);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

4.模拟调用

a.main方法调用

public static void main(String[] args) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("title", "freemarker&springboot");
        params.put("author", "tony");
        params.put("publishTime", "2018-02-09");
        params.put("seeNum", "888");
        params.put("imgPath", "http://5b0988e595225.cdn.sohucs.com/images/20181208/2c34c5244b5646418e658eacec7655df.jpeg");
        params.put("content", "freemarker静态页面生成");
    FreemarkerService.createHtml("test.ftl", "test.html", "D:\\freemarker", params);
    }

b.请求调用


import com.alibaba.fastjson.JSONObject;
import com.morewis.util.HttpServletUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Controller()
public class NewsFreemarkerController {

    @Value("${path}")
    private String folder;
    
    @Autowired
    PageDataService pageDataService;

    @RequestMapping("/createHtml")
    @ResponseBody
    public String createHtml() {
        HttpServletRequest request = HttpServletUtil.getRequest();

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("dao", pageDataService);

        String pageNumber = request.getParameter("pageNumber");
        String domainName = request.getParameter("domainName");
        
        //文件名称
        String targetFileName = "index.html";
        //路径名称
        String folderTemp = folder + File.separator + domainName;

        JSONObject jsonObject = new JSONObject();
        
        try {
            FreemarkerService.createHtml("template\\test.ftl", targetFileName, folderTemp, params);
            jsonObject.put("succes", true);
        	jsonObject.put("message", "创建成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("succes", false);
        	jsonObject.put("message", "创建失败:"+e.getMessage());
        }

        return jsonObject.toJSONString();
    }
    
}

4.模板代码(针对方案a)

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name='viewport'
          content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <title>Freemarker生成静态页面Demo展示</title>
    <style type="text/css">
        article {
            padding: 20px;
        }
        address {
            font-style: normal;
            text-align: right;
            width: 100%;
            color: #999999;
        }
        .author {
            float: left;
        }
        .seeIcon {
            padding: 0px 12px;
            background: url(imgs/see.png) no-repeat;
        }
        .seeNum {
            width: 100%;
        }
        .img {
            width: 380px;
            height: 380px;
        }
    </style>
</head>
<body>
<article>
    <h2>${title}</h2>
    <address>
        <span class="author">${author} ${publishTime}</span>
        <span class="seeIcon"></span>
        <span class="seeNum">${seeNum}</span>
    </address>
    <img src="${imgPath}" class="img"/>
    <p>${content}</p>
</article>
</body>
</html>

本篇仅作记录,如有错误,还望请大佬指教
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值