freemarker笔记

1. 网页静态化技术Freemarker

1.1 为什么要使用网页静态化技术

网页静态化解决方案在实际开发中运用比较多,例如新闻网站,门户网站中的新闻频道或者是文章类的频道。
对于电商网站的商品详细页来说,至少几百万个商品,每个商品又有大量的信息,这样的情况同样也适用于使用网页静态化来解决。
网页静态化技术和缓存技术的共同点都是为了减轻数据库的访问压力,但是具体的应用场景不同,缓存比较适合小规模的数据,而网页静态化比较适合大规模且相对变化不太频繁的数据。另外网页静态化还有利于SEO。
另外我们如果将网页以纯静态化的形式展现,就可以使用Nginx这样的高性能的web服务器来部署。Nginx可以承载5万的并发,而Tomcat只有几百。关于Nginx我们在后续的课程中会详细讲解。
今天我们就研究网页静态化技术----Freemarker 。

1.2 什么是 Freemarker

FreeMarker 是一个用 Java 语言编写的模板引擎,它基于模板来生成文本输出。FreeMarker与 Web 容器无关,即在 Web 运行时,它并不知道 Servlet 或 HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成 XML,JSP 或 Java 等。
在这里插入图片描述

1.3 Freemarker入门小DEMO

1.3.1 工程引入依赖, jar工程

<dependencies>
	  <dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.23</version>
	  </dependency>  
  </dependencies>
  <build>
	<plugins>			
		<!-- java编译插件 -->
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>3.2</version>
			<configuration>
				<source>1.7</source>
				<target>1.7</target>
				<encoding>UTF-8</encoding>
			</configuration>
	     </plugin>
	</plugins>
  </build>

1.3.2 创建模板文件

模板文件中四种元素
1、文本,直接输出的部分
2、注释,即<#–…-->格式不会输出
3、插值(Interpolation):即${…}部分,将使用数据模型中的部分替代输出
4、FTL指令:FreeMarker指令,和HTML标记类似,名字前加#予以区分,不会输出。
我们现在就创建一个简单的创建模板文件test.ftl

<html>
<head>
	<meta charset="utf-8">
	<title>Freemarker入门小DEMO </title>
</head>
<body>
<#--我只是一个注释,我不会有任何输出  -->
${name},你好。${message}
</body>
</html>

这里有文本、插值和注释

1.3.3 生成文件

使用步骤:
第一步:创建一个 Configuration 对象,直接 new 一个对象。构造方法的参数就是 freemarker的版本号。
第二步:设置模板文件所在的路径。
第三步:设置模板文件使用的字符集。一般就是 utf-8.
第四步:加载一个模板,创建一个模板对象。
第五步:创建一个模板使用的数据集,可以是 pojo 也可以是 map。一般是 Map。
第六步:创建一个 Writer 对象,一般创建一 FileWriter 对象,指定生成的文件名。
第七步:调用模板对象的 process 方法输出文件。
第八步:关闭流
代码:
创建Test类 main方法如下:

public static void main(String[] args) throws Exception{
	//1.创建配置类
	Configuration configuration=new Configuration(Configuration.getVersion());
	//2.设置模板所在的目录 
	configuration.setDirectoryForTemplateLoading(new File("D:\\itcastworkspaceMars-3\\freemarkerDemo\\src\\main\\resources"));
	//3.设置字符集
	configuration.setDefaultEncoding("utf-8");
	//4.加载模板
	Template template = configuration.getTemplate("test.ftl");
	//5.创建数据模型
	Map map=new HashMap();
	map.put("name", "张三 ");
	map.put("message", "欢迎来到神奇的品优购世界!");
	//6.创建Writer对象
	Writer out =new FileWriter(new File("d:\\test.html"));
	//7.输出
	template.process(map, out);
	//8.关闭Writer对象
	out.close();
}

执行后,在D盘根目录即可看到生成的test.html ,打开看看
在这里插入图片描述

1.4 FTL指令

1.4.1 assign指令

此指令用于在页面上定义一个变量
(1)定义简单类型:

<#assign linkman="周先生">
联系人:${linkman}

(2)定义对象类型:

<#assign info={"mobile":"13301231212",'address':'北京市昌平区王府街'} >
电话:${info.mobile}  地址:${info.address}

运行效果:
在这里插入图片描述

1.4.2 include指令

此指令用于模板文件的嵌套,创建模板文件head.ftl

<h1>信息网</h1>

我们修改test.ftl,在模板文件中使用include指令引入刚才我们建立的模板

<#include "head.ftl"/>

1.4.3 if指令

在模板文件上添加

<#if success=true>
  你已通过实名认证
<#else>  
  你未通过实名认证
</#if>

在代码中对success变量赋值

map.put("success", true);

在freemarker的判断中,可以使用= 也可以使用==

1.4.4 list指令

需求,实现商品价格表,如下图:
在这里插入图片描述
(1)代码中对变量goodsList赋值

List goodsList=new ArrayList();
		Map goods1=new HashMap();
		goods1.put("name", "苹果");
		goods1.put("price", 5.8);
		Map goods2=new HashMap();
		goods2.put("name", "香蕉");
		goods2.put("price", 2.5);
		Map goods3=new HashMap();
		goods3.put("name", "橘子");
		goods3.put("price", 3.2);
		goodsList.add(goods1);
		goodsList.add(goods2);
		goodsList.add(goods3);
		map.put("goodsList", goodsList);

(2)在模板文件上添加

----商品价格表----<br>
<#list goodsList as goods>
  ${goods_index+1} 商品名称: ${goods.name} 价格:${goods.price}<br>
</#list>

如果想在循环中得到索引,使用循环变量+_index就可以得到。

1.5 内建函数

内建函数语法格式: 变量+?+函数名称

1.5.1 获取集合大小

我们通常要得到某个集合的大小,如下图:
在这里插入图片描述
我们使用size函数来实现,代码如下:

共  ${goodsList?size}  条记录

1.5.2 日期格式化

代码中对变量赋值:

map.put("today", new Date());

在模板文件中加入

当前日期:${today?date} <br>
当前时间:${today?time} <br>   
当前日期+时间:${today?datetime} <br>        
日期格式化:  ${today?string("yyyy年MM月")}

运行效果如下:
在这里插入图片描述

1.5.3 数字转换为字符串

代码中对变量赋值:

map.put("point", 102920122);

修改模板:

累计积分:${point}

页面显示:
在这里插入图片描述
我们会发现数字会以每三位一个分隔符显示,有些时候我们不需要这个分隔符,就需要将数字转换为字符串,使用内建函数c

累计积分:${point?c}

页面显示效果如下:
在这里插入图片描述

1.6 空值处理运算符

如果你在模板中使用了变量但是在代码中没有对变量赋值,那么运行生成时会抛出异常。但是有些时候,有的变量确实是null,怎么解决这个问题呢?

1.6.1 判断某变量是否存在:“??”

用法为:variable??,如果该变量存在,返回true,否则返回false

<#if aaa??>
  aaa变量存在
<#else>
  aaa变量不存在
</#if>

1.6.2 缺失变量默认值:“!”

我们除了可以判断是否为空值,也可以使用!对null值做转换处理
在模板文件中加入

  ${aaa!'-'}

在代码中不对aaa赋值,也不会报错了 ,当aaa为null则返回!后边的内容-

1.7 运算符

1.7.1 算数运算符

FreeMarker表达式中完全支持算术运算,FreeMarker支持的算术运算符包括:+, - , * , / , %

1.7.2 逻辑运算符

逻辑运算符有如下几个:
逻辑与:&&
逻辑或:||
逻辑非:!
逻辑运算符只能作用于布尔值,否则将产生错误

1.7.3 比较运算符

表达式中支持的比较运算符有如下几个:
1 =或者==:判断两个值是否相等.
2 !=:判断两个值是否不等.
3 >或者gt:判断左边值是否大于右边值
4 >=或者gte:判断左边值是否大于等于右边值
5 <或者lt:判断左边值是否小于右边值
6 <=或者lte:判断左边值是否小于等于右边值
注意: =和!=可以用于字符串,数值和日期来比较是否相等,但=和!=两边必须是相同类型的值,否则会产生错误,而且FreeMarker是精确比较,“x”,"x ","X"是不等的.其它的运行符可以作用于数字和日期,但不能作用于字符串,大部分的时候,使用gt等字母运算符代替>会有更好的效果,因为 FreeMarker会把>解释成FTL标签的结束字符,当然,也可以使用括号来避免这种情况,如:<#if (x>y)>

1.8 用freemarker处理商品详情业务(红色箭头)

在这里插入图片描述

1.8.1 业务处理代码

1)service项目结构
在这里插入图片描述
2)applicatonContext-service.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--<context:component-scan base-package="com.pinyougou.page.service.impl"/>-->

	<dubbo:protocol name="dubbo" port="20885"></dubbo:protocol>
	<dubbo:application name="pinyougou-page-service"/>  
    <dubbo:registry address="zookeeper://192.168.200.128:2181"/>
    <dubbo:annotation package="cn.itcast.core.service" />
   
    <bean id="freemarkerConfig"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<!-- 配置模板所在目录位置 -->
		<property name="templateLoaderPath" value="/WEB-INF/ftl/" />
		<!-- 配置模板文件默认字符集 -->
		<property name="defaultEncoding" value="UTF-8" />
	</bean>
   
</beans>

3)实现接口方法

package cn.itcast.core.service;

import cn.itcast.core.dao.good.GoodsDao;
import cn.itcast.core.dao.good.GoodsDescDao;
import cn.itcast.core.dao.item.ItemCatDao;
import cn.itcast.core.dao.item.ItemDao;
import cn.itcast.core.pojo.good.Goods;
import cn.itcast.core.pojo.good.GoodsDesc;
import cn.itcast.core.pojo.item.Item;
import cn.itcast.core.pojo.item.ItemCat;
import cn.itcast.core.pojo.item.ItemQuery;
import com.alibaba.dubbo.config.annotation.Service;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.ServletContext;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CmsServiceImpl implements CmsService, ServletContextAware {

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private GoodsDescDao descDao;

    @Autowired
    private ItemDao itemDao;

    @Autowired
    private ItemCatDao catDao;

    private ServletContext servletContext;

    @Autowired
    private FreeMarkerConfigurer freemarkerConfig;

    @Override
    public void createStaticPage(Long goodsId, Map<String, Object> rootMap) throws Exception {
        //1. 获取模板的初始化对象
        Configuration configuration = freemarkerConfig.getConfiguration();
        //2. 获取模板对象
        Template template = configuration.getTemplate("item.ftl");

        //3. 创建输出流, 指定生成静态页面的位置和名称
        String path = goodsId + ".html";
        System.out.println("===path====" + path);
        String realPath = getRealPath(path);

        Writer out = new OutputStreamWriter(new FileOutputStream(new File(realPath)), "utf-8");
        //4. 生成
        template.process(rootMap, out);
        //5.关闭流
        out.close();

    }

    /**
     * 将相对路径转换成绝对路径
     * @param path  相对路径
     * @return
     */
    private String getRealPath(String path) {
        String realPath = servletContext.getRealPath(path);
        System.out.println("===realPath=====" + realPath);
        return realPath;
    }

    @Override
    public Map<String, Object> findGoodsData(Long goodsId) {
        Map<String, Object> resultMap = new HashMap<>();

        //1. 获取商品数据
        Goods goods = goodsDao.selectByPrimaryKey(goodsId);
        //2. 获取商品详情数据
        GoodsDesc goodsDesc = descDao.selectByPrimaryKey(goodsId);

        //3. 获取库存集合数据
        ItemQuery query = new ItemQuery();
        ItemQuery.Criteria criteria = query.createCriteria();
        criteria.andGoodsIdEqualTo(goodsId);
        List<Item> itemList = itemDao.selectByExample(query);

        //4. 获取商品对应的分类数据
        if (goods != null) {
            ItemCat itemCat1 = catDao.selectByPrimaryKey(goods.getCategory1Id());
            ItemCat itemCat2 = catDao.selectByPrimaryKey(goods.getCategory2Id());
            ItemCat itemCat3 = catDao.selectByPrimaryKey(goods.getCategory3Id());
            resultMap.put("itemCat1", itemCat1.getName());
            resultMap.put("itemCat2", itemCat2.getName());
            resultMap.put("itemCat3", itemCat3.getName());
        }
        //5. 将商品所有数据封装成Map返回
        resultMap.put("goods", goods);
        resultMap.put("goodsDesc", goodsDesc);
        resultMap.put("itemList", itemList);
        return resultMap;
    }

    /**
     * 由于当前项目是service项目, 没有配置springMvc所以没有初始化servletContext对象,
     * 但是我们这个项目配置了spring, spring中有servletContextAware接口, 这个接口中用servletContext对象
     * 这个是spring初始化好的, 所以我们实现servletContextAware接口, 目的是使用里面的servletContext对象给
     * 我们当前类上的servletContext对象赋值
     * @param servletContext
     */
    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }
}

4)Controller层代码
在运营商管理员在审核商品时,对审核通过的商品给与通过模板引擎动态生成根据商品id为名称的html页面,即为商品详情页面.
在这里插入图片描述
5)前端代码(angularjs)
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值