SSM综合项目实战(TTSC) -- day11 商品详情页,FreeMarker

一、搭建商品详情系统

1、商品详情分析

查看京东和天猫,发现主流电商的商品详情页都是独立的域名展示。

因为商品数量大,访问的频率很高,需要单独把商品详情分离出来,方便对商品详情功能进行扩容(增加集群数量)。

我们搭建表现层taotao-item-web即可,调用taotao-manager的服务,获取商品数据。

2、搭建商品详情系统






3、添加依赖




4、加入toccat插件




5、加入配置文件

注意:参照taotao-portal加入配置文件

springmvc.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:mvc="http://www.springframework.org/schema/mvc" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans.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.0.xsd  
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- 读取properties资源文件 -->
	<context:property-placeholder location="classpath:resources/env.properties" />

	<!-- 配置controller扫描 -->
	<context:component-scan base-package="com.taotao.item.controller" />

	<!-- 配置注解驱动 -->
	<mvc:annotation-driven />

	<!-- 配置视图解析器 ,配置前缀和后缀 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<!-- 配置dubbo服务 -->
	<dubbo:application name="taotao-item-web" />

	<!-- 使用广播 <dubbo:registry address="multicast://224.5.6.7:1234" /> -->
	<!-- 使用zookeeper注册中心 -->
	<dubbo:registry protocol="zookeeper" address="192.168.37.161:2181" />

	<!-- 声明要调用的服务,timeout是设置连接超时最长时间,如果不设置,超时时间默认是3秒 -->
	<dubbo:reference interface="com.taotao.manager.service.ItemService"
		id="itemService" timeout="1000000" />
	<dubbo:reference interface="com.taotao.manager.service.ItemDescService"
		id="itemDescService" timeout="1000000" />

</beans> 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	<display-name>taotao-item-web</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<!-- 解决POST乱码问题 -->
	<filter>
		<filter-name>encoding</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- 配置springMVC前端控制器 -->
	<servlet>
		<servlet-name>taotao-portal</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<!-- springMVC全局配置文件 -->
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring/springmvc.xml</param-value>
		</init-param>
		<!-- springmvc随着容器的启动而启动 -->
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>taotao-portal</servlet-name>
		<!-- 以.html结尾的请求进入SpringMVC,作用是用于SEO优化 -->
		<url-pattern>*.html</url-pattern>
	</servlet-mapping>
</web-app>

6、加入静态资源文件




7、项目整体预览




8、修改host文件中的域名




9、修改nginx配置文件的反向代理




二、实现商品详情页的动态展示

1、编写Controller代码

package com.taotao.item.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.taotao.manager.pojo.Item;
import com.taotao.manager.pojo.ItemDesc;
import com.taotao.manager.service.ItemDescService;
import com.taotao.manager.service.ItemService;

/**
 * 商品详情表现层
 * @author Administrator
 *
 */
@Controller
@RequestMapping("item")
public class ItemController {

	@Autowired
	private ItemService itemService;
	
	@Autowired
	private ItemDescService itemDescService;
	
	@RequestMapping(value="{itemId}", method=RequestMethod.GET)
	public String toItem(Model model, @PathVariable Long itemId){
		//使用商品服务查询商品
		Item item = this.itemService.queryById(itemId);
		
		ItemDesc itemDesc = this.itemDescService.queryById(itemId);
		
		//封装查询数据
		model.addAttribute("item", item);
		model.addAttribute("itemDesc", itemDesc);
		
		//返回结果视图
		return "item";
	}
}

2、测试运行




三、freemaker介绍

1、为什么要用静态化

商品详情页是消费者了解商品的主要途径,访问的频率非常高。所以需要对商品详情页进行优化,以提高访问的速度。

2、优化方案:

(1)、使用redis添加缓存

redis的访问速度快,能够较大的提升查询数据的速度,减轻MySQL数据库的访问压力。如果使用缓存的方式,需要注意数据同步的问题

(2)、使用静态化

把动态页面(jsp,php,asp等),转变成静态页面(html)

3、使用静态化的好处:

(1)、访问静态页面不需要经过程序处理,可以提高速度。(处理速度,和数据库访问速度)

(2)、稳定性高。

(3)、从安全角度讲,静态网页不易遭到黑客攻击。

(4)、静态页面相对于动态页面更容易被搜索引擎收录。(SEO)

4、静态化的访问流程




5、什么是freemarker

freemarker是java语言开发

freemarker是一个模板引擎,可以基于模板生成文本(html)

freemarker和应用服务器(Tomcat、jetty)是没有关联的,不需要使用jsp和servlet技术

freemarker除了前端页面展示的功能外,还可以生成xml,java

企业一般用freemarker做生成静态页面功能

freemarker文档地址




四、freemaker使用

1、创建maven工程






2、加入freemaker的依赖




3、创建freemaker模版文件




4、编写测试类

package cn.itcast.freemaker.test;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemakerTest {

	public static void main(String[] args) throws Exception {

		// 1.创建freemaker的核心对象
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
		
		// 2.给核心对象设置模版所在位置
		System.out.println(System.getProperty("user.dir"));
		cfg.setDirectoryForTemplateLoading(new File(System.getProperty("user.dir") + "/src/ftl"));
		
		// 3.使用核心对象获取模版对象,参数就是模版的名称
		// 官方要求模版必须是ftl类型,但是实际上任何后缀名都可以,只要保证内容是字符串即可
		Template template = cfg.getTemplate("test.html");
		
		// 4.创建数据模型,使用的是Map
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("value", "world");
		
		// 5.声明输出的Writer对象
		Writer out = new FileWriter(new File("H:/fremaker/result.html"));
		
		// 6.使用模版输出静态页面,需要两个参数,一个参数是模型数据,另一个是输出的Writer对象
		template.process(root, out);
	}
}

五、freemaker语法

1、封装javaBean数据

(1)、测试类代码




(2)、模版代码




(3)、测试效果



2、封装List数据

(1)、测试类代码




(2)、模版代码




(3)、测试效果



3、封装Map数据

(1)、测试类代码




(2)、模版代码




(3)、测试效果


4、封装List<Map>数据

(1)、测试类代码




(2)、模版代码




(3)、测试效果


5、封装date数据

(1)、测试类代码




(2)、模版代码




(3)、测试效果


6、带null的数据判断

(1)、测试类代码




(2)、模版代码




(3)、测试效果


7、include标签使用

(1)、模版代码






(2)、测试效果


六、商品详情静态化改造

1、在taotao-item-web中加入activeMQ的配置文件




2、改造web.xml中监听的配置文件




3、加入freemarker的配置文件


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jms="http://www.springframework.org/schema/jms" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

	<!-- 配置freemarker和spring整合 -->
	<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<!-- 设置模版编码 -->
		<property name="defaultEncoding" value="UTF-8" />
		<!-- 设置模版所在位置 -->
		<property name="templateLoaderPath" value="WEB-INF/ftl"></property>
	</bean>

</beans>

4、以item为模版改造静态页面模版



(1)、item.jsp的改造

a、删除jsp的声明头信息




b、将jsp的include标签替换为freemarker的include标签




(2)、将所有的模版中jsp信息全部改为freemarker的标签


footer.jsp




item.ftl




5、编写商品消息监听类




package com.taotao.item.message;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.manager.pojo.Item;
import com.taotao.manager.pojo.ItemDesc;
import com.taotao.manager.service.ItemDescService;
import com.taotao.manager.service.ItemService;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 静态化页面的监听类
 * @author Administrator
 *
 */
public class ItemMessageListener implements MessageListener {

	private static final ObjectMapper MAPPER = new ObjectMapper();

	@Override
	public void onMessage(Message message) {
		// 判断消息类型是否是TextMessage
		if (message instanceof TextMessage) {
			// 是,进行强转
			TextMessage textMessage = (TextMessage) message;

			try {
				// 获取消息
				String json = textMessage.getText();

				if (StringUtils.isNotBlank(json)) {
					// 解析json
					JsonNode jsonNode = MAPPER.readTree(json);
					// 获取操作符type
					String type = jsonNode.get("type").asText();
					// 获取商品id
					long itemId = jsonNode.get("itemId").asLong();
					// 进行消息的消费
					if ("save".equals(type)) {
						this.getHtml(itemId);
					}

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

	}

	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;

	@Autowired
	private ItemService itemService;

	@Autowired
	private ItemDescService itemDescService;

	/**
	 * 根据商品id进行静态化处理
	 * 
	 * @param itemId
	 * @throws Exception
	 */
	private void getHtml(long itemId) throws Exception {
		// 获取freemarker的核心对象
		Configuration cfg = this.freeMarkerConfigurer.getConfiguration();

		// 使用核心对象获取模版
		Template template = cfg.getTemplate("item.ftl");

		// 准备模版数据
		Map<String, Object> root = new HashMap<String, Object>();

		// 获取商品基础数据
		Item item = this.itemService.queryById(itemId);
		ItemDesc itemDesc = this.itemDescService.queryById(itemId);
		root.put("item", item);
		root.put("itemDesc", itemDesc);
		
		// 声明Writer输出对象
		Writer out = new FileWriter(new File("H:/fremaker/item/" + itemId + ".html"));

		// 使用模版输出静态页
		template.process(root, out);
	}

}

七、搭建静态资源服务器

1、修改nginx中item.taotao.com的配置




2、将静态资源文件导入到静态资源文件夹中




  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值