e3mall商城的归纳总结10之freemarker的使用和sso单点登录系统的简介

2023-05-24,,

敬给读者的话

本节主要讲解freemarker的使用以及sso单点登录系统,两种技术都是比较先进的技术,freemarker是一个模板,主要生成一个静态静态,能更快的响应给用户,提高用户体验。

而sso单点登录系统主要是为了解决分布式架构的一个登录系统,因为分布式架构的每一个模块都是一个项目,那么就需要存在一个session共享的问题,而sso单点登录系统正是为了解决这个问题。

1、使用freemarker实现网页静态化

2、ActiveMq同步生成静态网页

一、freemarker的使用方法

a、什么是freemarker

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

目前企业中:主要用Freemarker做静态页面或是页面展示

b、Freemarker的使用方法

把freemarker的jar包添加到工程中。

Maven工程添加依赖

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

原理图:

先设定好模板中的变量,然后在后台通过变量赋值然后生成一个静态文件的方式来产生一个静态html文件的。

使用步骤:

第一步:创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。

第二步:设置模板文件所在的路径。

第三步:设置模板文件使用的字符集。一般就是utf-8.

第四步:加载一个模板,创建一个模板对象。

第五步:创建一个模板使用的数据集,可以是pojo也可以是map。一般是Map。

第六步:创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。

第七步:调用模板对象的process方法输出文件。

第八步:关闭流。

我们来测试一下:

模板中我们只写了一个模板:

${hello}

hello为map中的key。

测试代码:

	@Test
public void genFile() throws Exception {
// 第一步:创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。
Configuration configuration = new Configuration(Configuration.getVersion());
// 第二步:设置模板文件所在的路径。
configuration.setDirectoryForTemplateLoading(new File("D:/workspaces/term197/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", "this is my first freemarker test.");
// 第六步:创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。
Writer out = new FileWriter(new File("D:/temp/term197/out/hello.html"));
// 第七步:调用模板对象的process方法输出文件。
template.process(dataModel, out);
// 第八步:关闭流。
out.close();
}

——模板的语法

比如说我们写了一个map,然后页面需要访问map中的key,那么模板中写${key}即可。

——访问pojo中的属性

Student对象。学号、姓名、年龄

上图需要将Student对象存入map中,map的key为stu,值为student的对象。比如

Student student = new Student(1,“小明”,18);//构造方法

Map mapdate = HaspMap<>();

mapdate.put(“stu”,student);

然后把map存入model中

——取集合中的数据

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

上图需要将list对象存入map中,map的key是studentList ,值是list对象。然后把map存入model中。

——取循环中的下标

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

——判断

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

如果序号是偶数,背景是蓝色,反正是红色。

——日期类型格式化

由于日期有很多格式,因此我们需要对日期进行格式修改

${date?date}表示date用日期表示,比如2019-1-22.

${date?time}表示date用时间表示 比如 23:00

${date?datetime}表示date用日期加时间表示比如 2019-1-22 23:00

${date?string(yyyy-MM-dd HH:mm:ss)}表示2019-01-22 23:00:00

——Null值的处理

由于freemarker中不能出现空值,因此我们需要对freemarker中的空值进行判断,

比如$ {myval!}表示当myval的值为空时,赋值“”(空字符串),和 $ {myval!""}类似。

<#if myval??>

myval中有内容

<#else>

myval为空

</#/if>

Include标签

<#include “模板名称”>

Freemarker整合spring

引入jar包:

Freemarker的jar包

整合spring

在spring目录下创建applicationContent-freemarker.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-4.2.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">
<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>

Controller层:

请求的url:/genhtml

参数:无

返回值:ok (String, 需要使用@ResponseBody)

业务逻辑:

1、从spring容器中获得FreeMarkerConfigurer对象。

2、从FreeMarkerConfigurer对象中获得Configuration对象。

3、使用Configuration对象获得Template对象。

4、创建数据集

5、创建输出文件的Writer对象。

6、调用模板对象的process方法,生成文件。

7、关闭流。

加载配置文件:

@Controller
public class HtmlGenController { @Autowired
private FreeMarkerConfigurer freeMarkerConfigurer; @RequestMapping("/genhtml")
@ResponseBody
public String genHtml()throws Exception {
// 1、从spring容器中获得FreeMarkerConfigurer对象。
// 2、从FreeMarkerConfigurer对象中获得Configuration对象。
Configuration configuration = freeMarkerConfigurer.getConfiguration();
// 3、使用Configuration对象获得Template对象。
Template template = configuration.getTemplate("hello.ftl");
// 4、创建数据集
Map dataModel = new HashMap<>();
dataModel.put("hello", "1000");
// 5、创建输出文件的Writer对象。
Writer out = new FileWriter(new File("D:/temp/term197/out/spring-freemarker.html"));
// 6、调用模板对象的process方法,生成文件。
template.process(dataModel, out);
// 7、关闭流。
out.close();
return "OK";
}
}

在项目中商品详情页面静态化

网页的静态化方案

输出文件的名称:商品id+“.html”

输出文件的路径:工程外部的任意目录。

网页访问:使用nginx访问网页。在此方案下tomcat只有一个作用就是生成静态页面。

工程部署:可以把e3-item-web部署到多个服务器上。

生成静态页面的时机:商品添加后,生成静态页面。可以使用Activemq,订阅topic(商品添加)

manager-service层添加商品:(发送Topic消息)

//添加商品
@Override
public E3Result InsertItem(TbItem item, String desc) {
final long id = IDUtils.genItemId();
//补齐数据
item.setId(id);
//1-正常,2-下架,3-删除
item.setStatus((byte) 1);
item.setCreated(new Date());
item.setUpdated(new Date());
TbItemMapper.insert(item);
TbItemDesc itemDesc = new TbItemDesc();
itemDesc.setItemId(id);
itemDesc.setItemDesc(desc);
itemDesc.setCreated(new Date());
itemDesc.setUpdated(new Date());
itemDescMapper.insert(itemDesc);
//向activemq中发送topic消息,广播一下
try {
jmsTemplate.send(topicDestination,new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
// 发送数据
TextMessage textMessgage = session.createTextMessage(id+"");
return textMessgage;
}
});
} catch (JmsException e) {
e.printStackTrace();
}
return E3Result.ok();
}

item-web接受topic消息

需要配置springmvcactivemq.xml(监听器、topicDestination、ConnectionFactory等等)和springmvcfreemarker.xml(freem的bean文件,构造方法等)配置文件。

package cn.tsu.item.e3mall.listener;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map; import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig; import cn.tsu.e3mall.common.Commons;
import cn.tsu.e3mall.pojo.TbItem;
import cn.tsu.e3mall.pojo.TbItemDesc;
import cn.tsu.e3mall.service.ItemService;
import cn.tsu.item.e3mall.pojo.Item;
import freemarker.template.Configuration;
import freemarker.template.Template; public class TopicListener implements MessageListener { @Autowired
private ItemService itemService; @Autowired
private FreeMarkerConfig freemarkerConfig; @Override
public void onMessage(Message message){
// TODO Auto-generated method stub
try {
Thread.sleep(1000);
TextMessage textMessage = (TextMessage) message;
String s = textMessage.getText();
Long itemid = new Long(s);
System.out.println("收到.....item-web"+itemid);
//查询商品信息
TbItem tbItem = itemService.getItemByid(itemid);
//继承tbItem,商品图片获取第一张getImages方法
Item item = new Item(tbItem);
//查询商品详情信息
TbItemDesc itemDesc = itemService.descEdit(itemid);
//获取configuration对象
Configuration configuration = freemarkerConfig.getConfiguration();
//通过configuration获取模板
Template template = configuration.getTemplate("item.ftl");
//创建map对象,把数据存入
Map dataModel = new HashMap<>();
dataModel.put("item", item);
dataModel.put("itemDesc", itemDesc);
//静态文件的名称
Writer out = new FileWriter(new File(Commons.ITEM_INFO+itemid+".html"));
//生成静态文件
template.process(dataModel, out);
//关流
out.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

三、sso系统分析

跳转到该文章

本文讲解的很详细,希望可以给您带来不同之处,如果您有问题,欢迎下方评论,博主看到后会第一时间回复大家.

e3mall商城的归纳总结10之freemarker的使用和sso单点登录系统的简介的相关教程结束。

《e3mall商城的归纳总结10之freemarker的使用和sso单点登录系统的简介.doc》

下载本文的Word格式文档,以方便收藏与打印。