Freemarker生成HTML模版页面

一 : 首先第一步
        放freemark的jar包

        <dependency>
            <groupId>org.freemarkergroupId>
            <artifactId>freemarkerartifactId>
            <version>2.3.20version>
        dependency>
二 : 第二步

新建包

将FreemarkerUtil放进去 
package cn.jbit.jd.freemarker;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemarkerUtil {


    public void createWord(String path,Map<String, Object> dataMap) {

        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");  
        // ========================获取模板=========================================
        configuration.setClassForTemplateLoading(FreemarkerUtil.class, "html"); // FTL文件所存在的位置
        Template t = null;
        try {
            t = configuration.getTemplate("index.ftl"); // 文件名
            t.setEncoding("UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //===========================生成页面========================================
        File outFile = new File(path);
        Writer out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(outFile),"UTF-8"));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            t.process(dataMap, out);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Index.ftl示例模版

<html>
<head>
<meta charset="UTF-8">
<title>${title}title>
<link rel="stylesheet" href="css/main.css">
head>
<body>
    <div class="top">div>
    
    <div class="menu">
        <div class="all-sort">
            <h2>
                <a href="">${alltype}a>
            h2>
        div>
        <div class="ad">
            <a href=""> <img
                src="images/rBEhVlJEA84IAAAAAAAZY9Mm2-UAADmFQNaVy4AABl7123.jpg"
                width="141" height="40" /> a>
        div>
        <div class="nav">
            <ul class="clearfix">
                <li><a href="http://sc.chinaz.com" class="current">${index}a>
                li>
                <li><a href="http://sc.chinaz.com">${dress}a>
                li>
                <li><a href="http://sc.chinaz.com">${supermarket}a>
                li>
                <li><a href="http://sc.chinaz.com">${teamBuy}a>
                li>
                <li><a href="http://sc.chinaz.com">${auction}a>
                li>
                <li><a href="http://sc.chinaz.com">${OnlineGame}a>
                li>
            ul>
        div>
    div>
    


            <#list goodsCetegory as goodsCetegory >
    <div class="wrap">
        <div class="all-sort-list">
            <div class="item bo">
                <h3><span>·span><a href="">${goodsCetegory.name}a>h3>
                <div class="item-list clearfix">
                    <div class="close">xdiv>
                    <div class="subitem">
                    <#list goodsTwoCetegory as goodsTwoCetegory >
                        <dl class="fore1">
                                <#if (goodsTwoCetegory.pid == goodsCetegory.id ) >
                                        <dt><a href="#">${goodsTwoCetegory.name }a>dt>
                                <#list goodsThreeeCetegory as goodsThreeeCetegory >
                                <#if (goodsThreeeCetegory.pid == goodsTwoCetegory.id) >
                                        <dd><em><a href="#">${goodsThreeeCetegory.name }a>em>dd>
                                    #if>
                                #list>
                                #if>
                        dl>
                    #list>
                    div>
                        
                        <div class="cat-right">
                            <dl class="categorys-promotions"
                                clstag="homepage|keycount|home2013|0601c">
                                <dd>
                                    <ul>
                                        <li><a href="#" target="_blank"><img
                                                src="images/rBEhWFJTydgIAAAAAAAiD8_1J3AAAD5mAMC0SYAACIn230.jpg"
                                                width="194" height="70" title="特价书满减"> a>
                                        li>
                                        <li><a href="#" target="_blank"><img
                                                src="images/rBEhVlJTyt8IAAAAAAAiq1D-0D8AAD7_gIE2KUAACLD102.jpg"
                                                width="194" height="70" title="重磅独家"> a>
                                        li>
                                    ul>
                                dd>
                            dl>
                            <dl class="categorys-brands"
                                clstag="homepage|keycount|home2013|0601d">
                                <dt>推荐品牌出版商dt>
                                <dd>
                                    <ul>
                                        <li><a href="#" target="_blank">中华书局a>
                                        li>
                                        <li><a href="#" target="_blank">人民邮电出版社a>
                                        li>
                                        <li><a href="#" target="_blank">上海世纪出版股份有限公司a>
                                        li>
                                        <li><a href="#" target="_blank">电子工业出版社a>
                                        li>
                                        <li><a href="#" target="_blank">三联书店a>
                                        li>
                                        <li><a href="#" target="_blank">浙江少年儿童出版社a>
                                        li>
                                        <li><a href="#" target="_blank">人民文学出版社a>
                                        li>
                                        <li><a href="#" target="_blank">外语教学与研究出版社a>
                                        li>
                                        <li><a href="#" target="_blank">中信出版社a>
                                        li>
                                        <li><a href="#" target="_blank">化学工业出版社a>
                                        li>
                                        <li><a href="#" target="_blank">北京大学出版社a>
                                        li>
                                    ul>
                                dd>
                            dl>
                        div>
                    div>
                div>
        div>
            #list>
    div>
    
    <script type="text/javascript" src="js/jquery.min.js">script>
    <script type="text/javascript">
        $('.all-sort-list > .item').hover(
                function() {
                    var eq = $('.all-sort-list > .item').index(this), //获取当前滑过是第几个元素
                    h = $('.all-sort-list').offset().top, //获取当前下拉菜单距离窗口多少像素
                    s = $(window).scrollTop(), //获取游览器滚动了多少高度
                    i = $(this).offset().top, //当前元素滑过距离窗口多少像素
                    item = $(this).children('.item-list').height(), //下拉菜单子类内容容器的高度
                    sort = $('.all-sort-list').height(); //父类分类列表容器的高度

                    if (item < sort) { //如果子类的高度小于父类的高度
                        if (eq == 0) {
                            $(this).children('.item-list').css('top', (i - h));
                        } else {
                            $(this).children('.item-list').css('top',
                                    (i - h) + 1);
                        }
                    } else {
                        if (s > h) { //判断子类的显示位置,如果滚动的高度大于所有分类列表容器的高度
                            if (i - s > 0) { //则 继续判断当前滑过容器的位置 是否有一半超出窗口一半在窗口内显示的Bug,
                                $(this).children('.item-list').css('top',
                                        (s - h) + 2);
                            } else {
                                $(this).children('.item-list').css('top',
                                        (s - h) - (-(i - s)) + 2);
                            }
                        } else {
                            $(this).children('.item-list').css('top', 3);
                        }
                    }

                    $(this).addClass('hover');
                    $(this).children('.item-list').css('display', 'block');
                }, function() {
                    $(this).removeClass('hover');
                    $(this).children('.item-list').css('display', 'none');
                });

        $('.item > .item-list > .close').click(function() {
            $(this).parent().parent().removeClass('hover');
            $(this).parent().hide();
        });
    script>
    <div style="text-align:center;clear:both">div>
body>
html>


test.ftl模版  (用于测试的模版)
<html>
<head>
<meta charset="UTF-8">
<title>京东新版侧栏jquery导航 - 站长素材title>
<link rel="stylesheet" href="css/main.css">
head>
<body>
<#list typeList as typeList >
        <a href="">${typeList.name} a>
#list>

body>
html>

Controller层
    /*
     * 跳转到freemarker生成的页面
     */
    @RequestMapping("toftlHtml")
    public String toftlHtml(){
        return "redirect:/index.html";
    }
    /*
     * 生成页面 test
     */
    @RequestMapping("makeHtml1")
    @ResponseBody
    public boolean makeHtml1(HttpServletRequest request,String name){
        System.out.println("--------------生成页面----------------");
        //查询数据
        ArrayList<Goods_cetegory> typeList = (ArrayList<Goods_cetegory>) this.goods_CetegoryService.getGoodsCetegory();
        HashMap<String,Object> map = new HashMap<String, Object>();
        map.put("typeList", typeList);

        //给定生成路径
        String path = request.getSession().getServletContext().getRealPath("/")+name+".html";
        System.out.println(path);
        //生成html
        FreemarkerUtil freemarkerUtil = new FreemarkerUtil();
        freemarkerUtil.createWord(path, map);

        return true;
    }
    /*
     * 生成页面
     */
    @RequestMapping("makeHtml")
    @ResponseBody
    public boolean makeHtml(HttpServletRequest req,String name){
        System.out.println("--------------生成页面----------------");
        //查询数据
        ArrayList<Goods_cetegory> goodsCetegory = (ArrayList<Goods_cetegory>) this.goods_CetegoryService.getGoodsCetegory();
        ArrayList<Goods_cetegory> goodsTwoCetegory = (ArrayList<Goods_cetegory>) this.goods_CetegoryService.getGoodsTwoCetegory();
        ArrayList<Goods_cetegory> goodsThreeeCetegory = (ArrayList<Goods_cetegory>) this.goods_CetegoryService.getGoodsThreeeCetegory();
        HashMap<String,Object> map = new HashMap<String, Object>();
        map.put("goodsCetegory", goodsCetegory);
        map.put("goodsTwoCetegory", goodsTwoCetegory);
        map.put("goodsThreeeCetegory", goodsThreeeCetegory);
        map.put("title","京东新版侧栏jquery导航 - 站长素材");
        map.put("alltype", "全部商品分类");
        map.put("index", "首页");
        map.put("dress", "服装");
        map.put("supermarket", "京东超市");
        map.put("teamBuy", "团购");
        map.put("auction", "拍卖");
        map.put("OnlineGame", "在线游戏");

        //给定生成路径
        String path = req.getSession().getServletContext().getRealPath("/")+name+".html";

        //生成html
        FreemarkerUtil freemarkerUtil = new FreemarkerUtil();
        freemarkerUtil.createWord(path, map);

        return true;
    }




<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<html>
  <head>

  <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery.min.js">script>head>
   <script type="text/javascript">

    $(function(){
        $("#makeHtml").click(function(){
            $.ajax({
                url:"<%=request.getContextPath()%>/makeHtml.action",
                type:"post",
                data:{
                    name : $("#fileName").val()
                },
                dataType:"json",
                success:function(ooo){
                    if(ooo){
                        alert("生成成功")
                    }
                    else{
                        alert("生成失败")
                    }
                }   
            });
        });
        $("#makeIndex").click(function(){
            location.href = "<%=request.getContextPath()%>/toftlHtml.action";
        });
    });

  script>

  <body>
    <input id ="fileName" />
    <button id = "makeHtml">生成页面button>
    <button id="makeIndex">查看页面button>
  body>


html>

后 : 最后一步 去查看html页面

你可能感兴趣的:(Freemarker)