freemarker生成静态页面

本文介绍如何使用Freemarker模板引擎结合Spring框架生成商品详情的静态页面,包括配置Freemarker、处理商品信息及图片展示,并解决了Maven打包时空文件夹不被包含的问题。

在这里插入图片描述创建详情工程,定义create静态页面cotroller

package com.qf.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qf.entity.Goods;
import com.qf.service.IGoodsService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
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.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @user ken
 * @date 2019/7/12 11:13
 */
@Controller
@RequestMapping("/item")
public class ItmeController {

    @Reference
    private IGoodsService goodsService;

    @Autowired
    private Configuration configuration;

    /**
     * 生成商品静态页
     */
    @RequestMapping("/createhtml")
    @ResponseBody
    public void createHtml(Integer gid, HttpServletRequest request) throws IOException {

        //根据商品id,查询商品的详细信息
        Goods goods = goodsService.queryById(gid);

        //根据freemarker生成商品的静态页面
        Template template = configuration.getTemplate("goodsitem.ftl");

        Map<String, Object> map = new HashMap<>();
        map.put("goods", goods);
        map.put("images", goods.getGimage().split("\\|"));
        map.put("contextPath", request.getContextPath());

        //获得classpath路径
        String path = ItmeController.class.getResource("/static").getPath().replace("20%"," ");
        System.out.println("获得的classpath路径为:" + path);
        //如果路径不存在,则创建
        File file = new File(path + "/page");
        if(!file.exists()){
            file.mkdirs();
        }


        try (
                Writer writer = new FileWriter(file.getAbsolutePath() + "/" + gid + ".html")
        ){
            template.process(map, writer);
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }
}

在这里插入图片描述静态页面,Template对象,传入map+写入流生成静态页面,到target/static/page 目录下

把流对象的创建放到try()中,程序会自动关流

上图程序运行会报空指针异常
maven编译打包的时候,空文件夹不会打包。所以会出现在启动运行测试的时候,明明创建了该文件夹,但是target中相应目录下,不会生成该文件,在用getResource方法去获取class path路径的时候,会报空指针异常
解决办法:手动生成不可行,可以在获取到static后,在判断的时候进行拼接+page,page文件夹不存在则生成

引入样式不能少斜杠 /

在这里插入图片描述实现添加商品就自动生成静态页,方式一

1、创建模拟http请求的工具类(在公共模块中创建,记得在商品详情页面引入common的依赖)

public class HttpUtil {

    /**
     * 模拟浏览器发送一个Get请求到指定的url服务器
     * @param urlStr
     * @return
     */
    public static String sendGet(String urlStr){

        try (
                ByteArrayOutputStream out = new ByteArrayOutputStream();
        ) {
            URL url = new URL(urlStr);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("GET");
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(10000);

            //发送请求到指定的服务器
            conn.connect();

            //获取服务器返回的结果
            InputStream in = conn.getInputStream();
            byte[] bytes = new byte[1024 * 10];
            int len;
            while((len = in.read(bytes)) != -1){
                out.write(bytes, 0, len);
            }

            byte[] buffer = out.toByteArray();

            return new String(buffer);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值