Freemarker使用

Freemaker技术

1.概要
1. Struts2默认使用freemarker实现自定义标签模板,项目导入Struts2,就已经导入的freemarker.
2. 模板引擎:
    1) 一种基于模板, 用来生成输出文件(任何来自于html的文本用来自动生成源代码)的通用工具.
    2) freemarker实际上被设计出来用来生成html页面;
    3) freemarker(模板文件) + java数据对象 == 输出(任何格式的文本);
3. freemarker模板文件, 通常扩展名为 .ftl;
2.开发
1. sts/eclipse中安装freemarker eclipse编辑插件
    将freemarker eclipse 复制到eclipse的dropins文件夹, 重启开发工具.
2. 编辑模板文件:
    通常模板文件放在 web-inf文件夹下 template;
    <html>
        <title>
            ${title}
        </title>
        <body>
            ${msg}
        </body>
    </html>
    ${变量}, 需要在程序中指定变量,合并到模板文件一同输出.
3.后台模板代码实现
@Test
public void testOutput(){
    //1. 配置对象, 配置模板位置
    Configuration configurarion = new Configuration(Configuration.VERSION_2_3_22);
    // 这一步是指定模板文件所在的目录
    configurarion.setDirectoryForTemplateLoading(
        new File("src/main/webapp/WEB-INF/templates"));
    //2. 获取模板对象
    Template template = configurarion.getTemplate("hello.ftl");
    //3. 动态数据对象
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("title","oranges");
    map.put("msg", "hello freemarker...");
    //4. 合并输出
    template.process(map, new PrintWriter(System.out));
}
4.实际案例
前端代码: 
1. promotion.html
<!--利用angularJS的路由功能--> 这里携带对象的id
<div class="caption">
    <p><a href="#/promotion_detail/{{item.id}}">{{item.title}}</a></p>
    <p class="text-right status">
        <span ng-show="item.status == '1'">进行中</span>
        <span ng-show="item.status == '2'">已结束</span>
    </p>
    <p class="text-right grey">{{item.startDate}}—{{item.endDate}}</p>
    <p class="text-right grey">{{item.activeScope}}</p>
</div>
2. index.html
<script type="text/javascript">
    var bosfore_app = angular.module("bosfore_app", ['ngRoute']);
    bosfore_app.config(["$routeProvider", function($routeProvider) {
        $routeProvider.when("/", {
            templateUrl: 'main.html'
        }).when("/order", {
            templateUrl: 'order.html'
        }).when("/express_manage", {
            templateUrl: 'express_manage.html'
        }).when("/userinfo", {
            templateUrl: 'userinfo.html'
        }).when("/search", {
            templateUrl: 'search.html'
        }).when("/myhome", {
            templateUrl: 'myhome.html'
        }).when("/promotion", {
            templateUrl: 'promotion.html'
        }).when("/promotion_detail/:id", {
            // 触发一个函数
            templateUrl: function ($routeParams) {
                return "promotion_showDetail.action?id=" + $routeParams.id;
            }
        }).otherwise({
            redirectTo: '/'
        })
    }]);
5.promotion_detail模板页面
<link rel="stylesheet" type="text/css" href="css/promotion_detail.css">
<div class="container promotions" >
    <div class="col-md-2 prolist">
        <h5 class="title"><a href="#/promotion"><strong>返回促销列表</strong></a></h5>
        <img src="images/pro.jpg" class="img-responsive">
    </div>
    <div class="col-md-1f0 procontent">
        <h5 class="title">${promotion.title}</h5>
        <div class="intro">
            <p>活动范围: ${promotion.activeScope}</p>
            <p>活动时间: ${promotion.startDate?string("yyyy-MM-dd")}
                - ${promotion.endDate?string("yyyy-MM-dd")}</p>
        </div>
        <div class="partline clearfix"></div>
        <div class="promotionbox">
            ${promotion.description}
        </div>
    </div>
</div>
6.后台代码
/**
     * 页面静态化的实现
     */
    @Action(value = "promotion_showDetail")
public String showDetail() throws Exception {
    //1. 先判断id对应的html文件是否存在, 如果存在就直接返回.
    String htmlRealPath = ServletActionContext.getServletContext().getRealPath("/freemarker");
            File htmlFile = new File(htmlRealPath + "/" + model.getId() + ".html");
    // 判断是否存在
    if(!htmlFile.exists()){
        //1. 配置对象, 配置模板位置
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
        //2. 这一步是指定模板文件所在的目录
        configuration.setDirectoryForTemplateLoading(new File(ServletActionContext.
                        getServletContext().getRealPath("/WEB-INF/template")));
        //3. 获取模板对象
        Template template = configuration.getTemplate("promotion_detail.ftl");

        //不存在, 需要查询数据库, 数据保存在bos_management中, 需要使用webService服务完成
        Promotion promotion = WebClient.create("http://localhost:9999/services/promotionService/promotion/"
                        + model.getId()).accept(MediaType.APPLICATION_JSON).get(Promotion.class);
        // 创建一个map集合
        Map<String, Object> map = new HashMap<>();
        map.put("promotion", promotion);
        // 合并输出
        template.process(map, new OutputStreamWriter(new FileOutputStream(htmlFile), "utf-8"));
            }
    // 设置文件的头信息
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType("text/html;charset=utf-8");
    //存在, 直接将文件返回
    FileUtils.copyFile(htmlFile, response.getOutputStream());
    return NONE;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值