Freemarker生成商品详情静态页面

男娘i 2022-05-28 01:37 380阅读 0赞
  1. Freemarker 模板引擎技术,是一种基于模板和数据生成可用的文本的工具。例如,我们可以通过定义 JavaBean 对象的格式,从数据库提取字段名称、类型,生成 JavaBean 对象。我们还可以用它生成静态的 html 页面,提供访问效率,例如电商网站商品详情页面,布局格式相同,只是内容不一样。
  2. 下面我会介绍 Freemarker 在电商网站生成商品详情页面的具体使用方法。

1.引入 jar 包

  1. <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
  2. <dependency>
  3. <groupId>org.freemarker</groupId>
  4. <artifactId>freemarker</artifactId>
  5. <version>2.3.23</version>
  6. </dependency>

2.创建 service 接口和实现

  1. package com.p7.framework.service;
  2. import java.util.Map;
  3. public interface StaticPageService {
  4. void createGoodsStaticHtml(Map<String, Object> root, String id);
  5. }
  6. package com.p7.framework.service.impl;
  7. import java.io.File;
  8. import java.io.FileNotFoundException;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.io.OutputStreamWriter;
  12. import java.io.UnsupportedEncodingException;
  13. import java.io.Writer;
  14. import java.util.Map;
  15. import javax.servlet.ServletContext;
  16. import org.apache.log4j.Logger;
  17. import org.springframework.web.context.ServletContextAware;
  18. import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
  19. import com.p7.framework.service.StaticPageService;
  20. import freemarker.template.Configuration;
  21. import freemarker.template.Template;
  22. import freemarker.template.TemplateException;
  23. public class StaticPageServiceImpl implements StaticPageService, ServletContextAware {
  24. private static final Logger logger = Logger.getLogger(StaticPageServiceImpl.class);
  25. private ServletContext servletContext;
  26. private Configuration conf;
  27. /** * 注入 SpringMVC 的 FreeMarkerConfigurer 启动配置类 */
  28. public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
  29. this.conf = freeMarkerConfigurer.getConfiguration();
  30. }
  31. /** * 注入 ServletContext ,获取路径 */
  32. public void setServletContext(ServletContext servletContext) {
  33. this.servletContext = servletContext;
  34. }
  35. /** * * @param root * 商品信息 * @param id * 商品 id */
  36. public void createGoodsStaticHtml(Map<String, Object> root, String id) {
  37. // 获取到路径
  38. String path = servletContext.getRealPath("/html/goods/detail/" + id + ".html");
  39. // 创建文件
  40. File f = new File(path);
  41. // 判断父文件夹存在不存在
  42. if (!f.getParentFile().exists()) {
  43. f.getParentFile().mkdirs();
  44. }
  45. // 输出流
  46. Writer out = null;
  47. // 创建输出流并指定编码UTF-8,此处的编码与
  48. try {
  49. out = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
  50. // 指定模板 返回模板对象 读UTF-8
  51. Template template = conf.getTemplate("freemarker.html");
  52. template.process(root, out);
  53. } catch (UnsupportedEncodingException e) {
  54. logger.error("UnsupportedEncodingException: " + e.getMessage());
  55. } catch (FileNotFoundException e) {
  56. logger.error("FileNotFoundException: " + e.getMessage());
  57. } catch (IOException e) {
  58. logger.error("IOException: " + e.getMessage());
  59. } catch (TemplateException e) {
  60. logger.error("TemplateException: " + e.getMessage());
  61. }
  62. }
  63. }

3.在 SpringMVC 配置文件中配置 FreeMarkerConfigurer

  1. // 在 Freemarker 入门程序中创建的 Configuration ,用来设置模板的加载目录,这个路径必须写成绝对路径。
  2. // Configuration conf = new Configuration();
  3. // conf.setDirectoryForTemplateLoading(new File("E:/ws/framework/demo/ftl/"));
  4. // 但是在实际的项目开发中,我们不可能使用这样一个路径,
  5. // 因此,我们需要借助其他方法,例如 SpringMVC 中有 FreeMarkerConfigurer 这样的一个类
  6. <!-- Freemarker 配置 -->
  7. <bean id="staticPageService" class="com.p7.framework.service.impl.StaticPageServiceImpl">
  8. <!-- 注入FreeMarkerConfigurer -->
  9. <property name="freeMarkerConfigurer">
  10. <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
  11. <!-- 采用相对路径来设置模板目录 -->
  12. <property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
  13. </bean>
  14. </property>
  15. </bean>
  16. <!-- 配置静态资源访问 -->
  17. <mvc:resources mapping="/resources/**" location="/" />

这里写图片描述

4.controller 层
由于是测试,直接访问该接口,弄一些测试数据。

  1. package com.p7.framework.controller;
  2. import java.math.BigDecimal;
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import java.util.Map;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Controller;
  9. import org.springframework.web.bind.annotation.GetMapping;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import com.p7.framework.service.StaticPageService;
  12. @Controller
  13. @RequestMapping("/freemarker")
  14. public class FreemarkerController {
  15. @Autowired
  16. private StaticPageService staticPageService;
  17. @GetMapping()
  18. public void createGoodsStaticHtml() {
  19. String id = "7758521";
  20. Map<String, Object> root = new HashMap<String, Object>();
  21. List<String> sizes = new ArrayList<String>();
  22. sizes.add("s");
  23. sizes.add("xl");
  24. sizes.add("xxl");
  25. root.put("goodsName", "苍**同款ww");
  26. root.put("goodsPrice", new BigDecimal("100.00"));
  27. root.put("crowd", "you just can't keep it in your pants!");
  28. root.put("imgSrc", "xxoo");
  29. root.put("sizes", sizes);
  30. staticPageService.createGoodsStaticHtml(root, id);
  31. }
  32. }

5.项目结构
这里写图片描述

6.模板内容
因为只是测试,所以模板内容只是简单的一些文本输出。实际的应用中,模板内容是包含了引入的 js、css 等等的文件。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5. <title>Insert title here</title>
  6. </head>
  7. <body>
  8. 商品名称:${goodsName}
  9. 商品价格:${goodsPrice}
  10. 适合人群:${crowd}
  11. 商品尺码:
  12. <#list sizes as size>
  13. ${size}
  14. </#list>
  15. 商品图片:<img src="${imgSrc}">
  16. </body>
  17. </html>

7.测试

  1. 测试通过模板和数据生成静态页面。
  2. # resources 是映射的静态路径的相对跟路径,也就是在配置文件中配置的
  3. # <mvc:resources mapping="/resources/**" location="/" />
  4. http://localhost:8080/项目名/freemarker
  5. http://localhost:8080/项目名/resources/html/goods/detail/7758521.html
  6. <!DOCTYPE html>
  7. <html>
  8. <head>
  9. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  10. <title>Insert title here</title>
  11. </head>
  12. <body>
  13. 商品名称:苍**同款ww
  14. 商品价格:100
  15. 适合人群:you just can't keep it in your pants!
  16. 商品尺码:
  17. s
  18. xl
  19. xxl
  20. 商品图片:<img src="xxoo">
  21. </body>
  22. </html>

8.说明
在实际的电商应用中,一般情况下,静态的商品详情页在点击商品上架时,生成静态页面,也就是说,在上架的接口中获取到商品的信息,调用 StaticPageService 的方法生成静态页面。
在访问电商主页或者查询商品时,我们也需要对静态页面的 url 作一些处理

  1. <a href="javascript:void(0)" onclick="window.open('http://localhost:8080/resources/html/goods/detail/${goods.id}.html')"

发表评论

表情:
评论列表 (有 0 条评论,380人围观)

还没有评论,来说两句吧...

相关阅读