Freemarker(下)

简介: Freemarker(下)

4. Freemarker整合spring

4.1. 创建整合spring的配置文件


<?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" />
        <property name="freemarkerSettings">
            <!-- 设置默认的编码方式,原先是GBK,需要设置成utf-8 -->
            <props>
                    <!--用于解决前端报空指针问题 不用再空值后面+ !号-->
                <prop key="classic_compatible">true</prop>
               <!--  <prop key="defaultEncoding">utf-8</prop>
                <prop key="template_exception_handler">rethrow</prop> -->
            </props>
        </property>
    </bean>
</beans>


需要编写一Controller进行测试


4.2 Controller

请求的url:/genhtml

参数:无

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

业务逻辑:

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

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

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

4、创建数据集

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

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

7、关闭流。


加载配置文件:


image.png


@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";
    }
}


5. 商品详情页面静态化

5.1 网页的静态化方案

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

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

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

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

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



微信图片_20220127194014.png

微信图片_20220127194014.png


3.5.2. MessageListener

需要实现MessageListener,把Active的客户端jar包的依赖添加到工程中。

业务逻辑:

1、创建一个MessageListener接口的实现类

2、从message中取商品id

3、查询商品基本消息、商品描述。

4、创建商品详情页面的模板。

5、指定文件输出目录

6、生成静态文件。

安装http服务器。


public class HtmlGenListener implements MessageListener {
    @Autowired
    private ItemService itemService;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${HTML_OUT_PATH}")
    private String HTML_OUT_PATH;
    @Override
    public void onMessage(Message message) {
        try {
            // 1、创建一个MessageListener接口的实现类
            // 2、从message中取商品id
            TextMessage textMessage = (TextMessage) message;
            String strItemId = textMessage.getText();
            Long itemId = new Long(strItemId);
            // 3、查询商品基本消息、商品描述。
            TbItem tbItem = itemService.getItemById(itemId);
            Item item = new Item(tbItem);
            TbItemDesc tbItemDesc = itemService.getItemDescById(itemId);
            //创建数据集
            Map data = new HashMap<>();
            data.put("item", item);
            data.put("itemDesc", tbItemDesc);
            // 4、创建商品详情页面的模板。
            // 5、指定文件输出目录
            Configuration configuration = freeMarkerConfigurer.getConfiguration();
            Template template = configuration.getTemplate("item.htm");
            FileWriter out = new FileWriter(new File(HTML_OUT_PATH + itemId + ".html"));
            // 6、生成静态文件。
            template.process(data, out);
            //关闭流
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


3.5.3. Spring配置文件


<?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: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.2.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
    <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供 -->
    <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://192.168.25.168:61616" />
    </bean>
    <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
    <bean id="connectionFactory"
        class="org.springframework.jms.connection.SingleConnectionFactory">
        <!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->
        <property name="targetConnectionFactory" ref="targetConnectionFactory" />
    </bean>
    <!--这个是主题目的地,一对多的 -->
    <bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg value="item-add-topic" />
    </bean>
    <!-- 配置消息监听器 -->
    <bean id="htmlGenListener" class="com.taotao.item.listener.HtmlGenListener"/>
    <!-- 配置监听容器 -->
    <!-- 消息监听容器 -->
    <bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="destination" ref="topicDestination" />
        <property name="messageListener" ref="htmlGenListener" />
    </bean>
</beans>
目录
相关文章
|
XML 移动开发 API
微信支付开发(7) H5支付
关键字:微信支付 微信支付v3 H5支付 wap支付 prepay_id 作者:方倍工作室原文: http://www.cnblogs.com/txw1958/p/wxpayv3_h5.html    本文介绍微信支付下的H5支付实现流程。
3790 1
|
12月前
|
Java 数据库连接 Maven
最新版 | 深入剖析SpringBoot3源码——分析自动装配原理(面试常考)
自动装配是现在面试中常考的一道面试题。本文基于最新的 SpringBoot 3.3.3 版本的源码来分析自动装配的原理,并在文未说明了SpringBoot2和SpringBoot3的自动装配源码中区别,以及面试回答的拿分核心话术。
最新版 | 深入剖析SpringBoot3源码——分析自动装配原理(面试常考)
|
Kubernetes Linux Docker
容器化技术Docker入门与实践
容器化技术Docker入门与实践
197 20
|
Go 微服务
Go语言微服务框架 - 3.日志库的选型与引入
衡量日志库有多个指标,我们今天重点关注两点:简单易用 与 高性能。简单易用是一个日志库能被广泛使用的必要条件,而高性能则是企业级的日志库非常重要的衡量点,也能在源码层面对我们有一定的启发。
891 1
|
安全 前端开发 Java
Spring Security的授权管理器实现
Spring Security的授权管理器涉及用户登录后的token验证和权限检查。当用户携带token访问时,框架会验证token合法性及用户访问权限。自定义授权管理器`TokenAuthorizationManager`需实现`AuthorizationManager&lt;RequestAuthorizationContext&gt;`接口,处理校验逻辑,包括解析token、判断用户角色与访问资源的匹配。配置中在`SecurityConfig`注册该管理器以生效。测试表明,具有不同角色的用户可访问相应权限的资源,否则返回403错误。
441 4
|
存储 JavaScript 安全
|
数据采集 分布式计算 数据挖掘
数据收集与整合
数据收集与整合
359 2
|
JavaScript
GitHub——自动发布NPM包
GitHub——自动发布NPM包
228 0
|
存储 运维 资源调度
分布式交换机其实可以这么玩!
分布式交换机其实可以这么玩!