e3mall项目第十天——freemarker网页静态化

今日内容一:网页静态化

可以使用Freemarker实现网页静态化。

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

Freemarker的使用方法
把freemarker的jar包添加到工程中。

<dependency>
  <groupId>org.freemarker</groupId>
  <artifactId>freemarker</artifactId>
  <version>2.3.23</version>
</dependency>

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

/**
 * freemarker的测试
 * <p>Title: TestFreemarker</p>
 * <p>Description: </p>
 * <p>Company: www.itcast.cn</p> 
 * @version 1.0
 */
public class TestFreemarker {
	@Test
	public void genFile() throws Exception{
		// 第一步:创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。
		Configuration configuration = new Configuration(Configuration.getVersion());
		// 第二步:设置模板文件所在的路径。
		configuration.setDirectoryForTemplateLoading(new File("D:/workspace-E3/java-e3mall/e3-item-web/src/main/webapp/WEB-INF/ftl"));
		// 第三步:设置模板文件使用的字符集。一般就是utf-8.
		configuration.setDefaultEncoding("utf-8");
		// 第四步:加载一个模板,创建一个模板对象。
		Template template = configuration.getTemplate("hello.ftl");
		// 第五步:创建一个模板使用的数据集,可以是pojo也可以是map。一般是Map。
		Map dataModel = new HashMap<>();
		//向数据集中添加数据
		dataModel.put("hello", "test1");
		// 第六步:创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。
		Writer out = new FileWriter(new File("D:/Freemarker/freemarker/hello.txt"));
		// 第七步:调用模板对象的process方法输出文件。
		template.process(dataModel, out);
		// 第八步:关闭流。
		out.close();
	}
}

模板的语法:
访问map中的key:${key}

访问pojo中的属性:
Student对象。学号、姓名、年龄 ${key.property}

取集合中的数据:

<#list studentList as student>
${student.id}/${studnet.name}
</#list>

取循环中的下标:

<#list studentList as student>
	${student_index}
</#list>

判断:

<#if student_index % 2 == 0>
<#else>
</#if>

日期类型格式化:

当前日期:${data?data}
当前日期:${data?time}
当前日期和时间:${data?datatime}
自定义日期格式:${data?string(yyyy/MM/dd HH:mm:ss)}

Include标签:

<!-- hello.ftl相当于一个html-->
<#include hello.ftl>

今日内容二:Freemarker整合spring

引入Freemarker的jar包

<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context</artifactId>
</dependency>

整合Freemarker和springmvc的配置文件:

<?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-4.2.xsd
		http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

	<!-- 加载配置文件 -->
	<context:property-placeholder location="classpath:conf/resource.properties" />
	
	<context:component-scan base-package="cn.e3mall.item.controller" />
	<mvc:annotation-driven />
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
	<!-- 配置freemarker -->
	<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>
	
	<!-- 引用dubbo服务 -->
	<dubbo:application name="e3-item-web"/>
	<dubbo:registry protocol="zookeeper" address="192.168.25.128:2181"/>	
	<dubbo:reference interface="cn.e3mall.service.ItemService" id="itemService" />
</beans>

Controller进行测试:
请求的url:/genhtml
参数:无
返回值:ok (String, 需要使用@ResponseBody)
业务逻辑:
1、从spring容器中获得FreeMarkerConfigurer对象。
2、从FreeMarkerConfigurer对象中获得Configuration对象。
3、使用Configuration对象获得Template对象。
4、创建数据集
5、创建输出文件的Writer对象。
6、调用模板对象的process方法,生成文件。
关闭流。

测试代码:

/**
 * 生成静态页面测试controller
 * <p>Title: HtmlGenController</p>
 * <p>Description: </p>
 * <p>Company: www.itcast.cn</p> 
 * @version 1.0
 */
@Controller
public class HtmlGenController {
	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;
	
	@RequestMapping("/genhtml")
	@ResponseBody
	public String genHtml() throws Exception{
		// 请求的url:/genhtml
		// 参数:无
		// 返回值:ok (String, 需要使用@ResponseBody)
		// 业务逻辑:
		// 1、从spring容器中获得FreeMarkerConfigurer对象。
		Configuration configuration = freeMarkerConfigurer.getConfiguration();
		// 2、从FreeMarkerConfigurer对象中获得Configuration对象。
		// 3、使用Configuration对象获得Template对象。
		Template template = configuration.getTemplate("hello.ftl");
		// 4、创建数据集
		Map map = new HashMap<>();
		map.put("hello", 123456);
		// 5、创建输出文件的Writer对象。
		Writer out = new FileWriter(new File("D:/Freemarker/freemarker/hello3.html"));
		// 6、调用模板对象的process方法,生成文件。
		template.process(map, out);
		// 关闭流
		out.close();
		return "ok";
	}
	
}

今日内容三:商品详情页面静态化

网页的静态化方案;
输出文件的名称:商品id+“.html”
输出文件的路径:工程外部的任意目录。
网页访问:使用nginx访问网页。在此方案下tomcat只有一个作用就是生成静态页面。
工程部署:可以把e3-item-web部署到多个服务器上。
生成静态页面的时机:商品添加后,生成静态页面。可以使用Activemq,订阅topic(商品添加)

流程图:
在这里插入图片描述
相关代码:
准备工作:
把jsp改造为freemarker模板:略(按照freemarker模版的语法去改就行了)

代码相关的配置文件:
springmvc里面的freemarker配置:

<!-- 配置freemarker -->
	<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>

代码里面的配置,有利于后期的维护:
注意加载配置文件

#静态页面输出位置
HTML_GEN_PATH=D:/Freemarker/freemarker/item/
/**
 * 监听商品添加消息,生成对应的静态页面
 * <p>Title: HtmlGenListener</p>
 * <p>Description: </p>
 * <p>Company: www.itcast.cn</p> 
 * @version 1.0
 */
public class HtmlGenListener implements MessageListener {
	
	@Autowired
	private ItemService itemService;
	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;
	@Value("${HTML_GEN_PATH}")
	private String HTML_GEN_PATH;
	
	@Override
	public void onMessage(Message message) {
		try {
			//从消息中取商品id
			TextMessage textMessage = (TextMessage) message;
			String text = textMessage.getText();
			Long itemId = new Long(text);
			//等待事务提交
			Thread.sleep(1000);
			//根据商品id查询商品信息,商品基本信息和商品描述
			TbItem tbItem = itemService.getItemById(itemId);
			//将tbitem转换成item(item是对TbItem的拓展)
			Item item = new Item(tbItem);
			//取商品描述
			TbItemDesc itemDesc = itemService.getItemDescById(itemId);
			//创建一个数据集,把商品数据封装
			Map data = new HashMap<>();
			data.put("item", item);
			data.put("itemDesc", itemDesc);
			//加载模版对象
			Configuration configuration = freeMarkerConfigurer.getConfiguration();
			Template template = configuration.getTemplate("item.ftl");
			//创建一个输出流,指定输出的目录以及文件名
			Writer out = new FileWriter(HTML_GEN_PATH + itemId + ".html");
			//生成静态页面
			template.process(data, out);
			//关闭流
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值