创建详情工程,定义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;
}

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

1438

被折叠的 条评论
为什么被折叠?



