FreeMarker生成静态HTML页面的工具类FreeMarkerUtil

什么是freemarker

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

 添加依赖

<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.23</version>
</dependency>

FreeMarkerUtil工具类:

import com.huaxia.entity.News;  
import com.huaxia.entity.User;  
import freemarker.template.Configuration;  
import freemarker.template.Template;  
import freemarker.template.TemplateException;  
  
import javax.servlet.http.HttpServletRequest;  
import java.io.*;  
import java.util.HashMap;  
import java.util.Locale;  
import java.util.Map;  
  
/** 
 * 创建人: leon 
 * 创建时间: 2014年11月28日 上午10:07:51 
 * 类描述:Freemarker的工具类 
 */  
public class FreemarkerUtil {  
  
    /** 
     * 通过指定的名字获取相应的模板 
     * @param fileName 
     * @return 
     */  
    public Template getTemplate(HttpServletRequest request,String fileName) {  
        try {  
        Configuration cfg = new Configuration();  
        cfg.setOutputEncoding("UTF-8");  
        cfg.setDefaultEncoding("UTF-8");// 编码设置1    
        cfg.setEncoding(Locale.CHINA, "UTF-8");  
        //设定读取ftl模板文件的目录  
        //cfg.setClassForTemplateLoading(this.getClass(), "/template");     //读取src目录下  
        cfg.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/template"); //读取webroot目录下  
        //在模板文件目录中找到名称为name的文件,并加载为模板  
        Template template = cfg.getTemplate(fileName);  
        template.setEncoding("UTF-8");// 编码设置2  
        return template;  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return null;  
    }  
      
    /** 
     * 通过指定的文件目录和文件名生成相应的文件 
     * @param fileDir 
     * @param fileName 
     */  
    public Boolean printToFile(Template template,String fileDir,String fileName,Map<String,Object> root) {  
        boolean done = false;  
        Writer writer = null;  
        try {  
            //判断多级目录是否存在,不存在则一级级创建  
            String[] paths = fileDir.split("\\\\");//注意:此处“\\”是错误的,必须要“\\\\”才能分割字符串  
            String dir = paths[0];  
            for (int i = 1; i < paths.length; i++) {  
                dir = dir + File.separator + paths[i];  
                File file=new File(dir.toString());  
                if (!file.exists()) {  
                    file.mkdir();  
                }  
            }  
            //创建输出流  
            File file = new File(fileDir +File.separator+ fileName);    
                 
            //设置生成的文件编码为UTF-8     
            //服务器不支持UTF-8格式HTML时候使用ANSI格式HTML文件,即系统默认编码     
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));  // 编码设置3  
            //writer = new FileWriter(fileDir +File.separator+ fileName);  
            //输出模板和数据模型都对应的文件  
            template.process(root, writer);  
            done = true;  
        } catch (IOException e) {  
            e.printStackTrace();  
        } catch (TemplateException e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if(writer!=null){  
                    writer.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return done;  
    }  
      
    /** 
     * 通过传入的请求和新闻信息重新生成html文件 
     * @param news  //新闻实体类 
     * @param request   //请求 
     * @param user  //用户 
     * @return 
     */  
    public boolean genenateHtml(News news,HttpServletRequest request,User user) {  
        String fileName = news.getFileName();  
        Map<String, Object> root = new HashMap<String, Object>();  
        root.put("id", news.getId());  
        root.put("title", news.getTitle());  
        root.put("create_date", news.getCreateDate());  
        root.put("creator", news.getCreator());  
        root.put("content", ClobUtil.ClobToString(news.getContent()));  
        root.put("fileName", news.getUploadFile()==null?"":news.getUploadFile());  
        FreemarkerUtil freemarkerUtil = new FreemarkerUtil();  
        Template template = null;  
        template = freemarkerUtil.getTemplate(request, "news.ftl");//新闻发布系统的freemarker模板  
        String htmlDir = news.getDir();  
        boolean done = printToFile(template, htmlDir, fileName, root);  
        return done;  
    }  
}  

MT实战

package cn.maitian.maimai.system.web.action;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.maitian.bss.duty.privilege.utils.SpringContextHolder;
import cn.maitian.maimai.core.base.bean.MethodCallBack;
import cn.maitian.maimai.core.base.vo.FileUploadVo;
import cn.maitian.maimai.core.base.web.BaseAction;
import cn.maitian.maimai.core.util.AppDatePattern;
import cn.maitian.maimai.core.util.AppDateUtil;
import cn.maitian.maimai.core.util.AppFileUploadUtils;
import cn.maitian.maimai.core.util.AppPropPublicUtil;
import cn.maitian.maimai.core.util.AppPropUtil;
import cn.maitian.maimai.core.util.AppStringUtils;
import cn.maitian.maimai.core.util.FreeMarkertUtil;
import cn.maitian.maimai.core.util.ImageBase64Utils;
import cn.maitian.maimai.system.model.SysContacts;
import cn.maitian.maimai.system.service.SysContactsIService;
import cn.maitian.maimai.system.vo.AppDataShareVo;
import cn.maitian.stat.service.CallProcedureIService;
import cn.maitian.webx.web.annotation.Read;
import cn.maitian.webx.web.data.Scope;
import cn.maitian.webx.web.data.WebxWebData;

/**
 * H5链接跳转
 * */
public class AppForHtmlFiveAction extends BaseAction {

    private SysContactsIService sysContactsIService;

    /**
     * 用户数据分享活动
     */
    private static final String PER_DATA_SHARE = "{call PER_DATA_SHARE (?,?)}";
    /**
     * 数据分享模板
     */
    private static final String DATA_SHARE_INFO_FTL = "dataShareInfo.ftl";
    /**
     * 业务类型, 1-数据分享
     */
    private static final String BUSINESS_TYPE_DATA_SHARE = "1";
    /**
     * 文件扩展名称 -html
     */
    private static final String FILE_EXT_NAME_HTML = ".html";
    /**
     * 文件扩展名称 -Pic
     */
    private static final String FILE_EXT_NAME_PIC = ".jpg";

    /**
     *  数据分享 链接跳转H5
     * 
     * @param userId 用户Id
     * @param source 业务来源(Loading-1、轮播图-2)
     * @return String /maimai/appForHtmlFiveAction.do?method=dataShareInfo&source=&userId=
     */
    public String dataShareInfo(@Read(key = "userId") final String userId, @Read(key = "source") final String source) {
        long begTime = System.currentTimeMillis();
        logger.error("--->>>---数据分享 链接跳转H5---<<<---userId:" + userId);
        JSONArray reqParam = new JSONArray();
        JSONObject jo = new JSONObject();
        jo.put("userId", userId);
        reqParam.add(jo);
        // 查询用户数据分享页数据
        AppDataShareVo adsv = findUserShareData(userId);
        adsv.setSource(source);
        getAttributeUtil().setAttribute("vo", Scope.REQUEST, adsv);
        long endTime = System.currentTimeMillis();
        logger.error("--- 数据分享 链接跳转H5---dataShareInfo---method out---> {" + (endTime - begTime) + "}");
        return "dataShareInfo";
    }

    /**
     * 去分享并生成静态页面
     * 
     * @param userId 用户Id
     * @return String
     */
    public String toDataSharePage(@Read(key = "userId") final String userId) {
        long begTime = System.currentTimeMillis();
        Map<String, Object> result = new HashMap<String, Object>();
        // 查询用户数据分享页数据
        AppDataShareVo adsv = findUserShareData(userId);
        String jsonString = JSON.toJSONString(adsv);
        
        String basePath = AppPropUtil.getPropValue(AppPropUtil.Keys.FILE_UPLOAD_HTTP);
        String staticPageUploadPath = AppPropPublicUtil.getPropValue(AppPropPublicUtil.Keys.STATIC_PAGE_UPLOAD_PREFIX);
        
        String fileName = getDatePath(userId, BUSINESS_TYPE_DATA_SHARE, FILE_EXT_NAME_HTML);
        String fileOutUrl = basePath + staticPageUploadPath + "/" + userId;
        String picPrefix = AppPropUtil.getPropValue(AppPropUtil.Keys.DOWNLOAD_FILE_HTTP);
        String fullPath = picPrefix + staticPageUploadPath + "/" + userId + "/" + fileName;;
        // 生成静态页面
        FreeMarkertUtil.processTemplate(DATA_SHARE_INFO_FTL, JSON.parseObject(jsonString), fileOutUrl, fileName);
        result.put("file", fullPath);
        result.put("success", "true");
        renderText(dataToJson(result));
        long endTime = System.currentTimeMillis();
        logger.error("--- 去分享并生成静态页面---toDataSharePage---method out---> {" + (endTime - begTime) + "}");
        return null;
    }

    /**
     * 数据分享上传生成的图片
     * 
     * @param userId 用户Id
     * @return String
     */
    public String uploadDataSharePic(@Read(key = "userId") final String userId) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            HttpServletRequest request = WebxWebData.getStrutsWebData().getRequest();
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (!isMultipart) {
                result.put("success", "false");
                renderText(dataToJson(result));
                return null;
            }
            DefaultMultipartHttpServletRequest dmhsr = (DefaultMultipartHttpServletRequest) request;
            Map<String, MultipartFile> map = dmhsr.getFileMap();
            MultipartFile cmf = map.get("file");
            if (cmf.getOriginalFilename().contains(".")) {
                String fileName[] = cmf.getOriginalFilename().split("\\.");
                String sux = fileName[fileName.length - 1];
                if (!"jpg".equalsIgnoreCase(sux) && !"png".equalsIgnoreCase(sux)
                        && !"JPEG".equalsIgnoreCase(sux) && !"bmp".equalsIgnoreCase(sux)) {
                    result.put("success", "false");
                    renderText(dataToJson(result));
                    return null;
                }
            }

            List<FileUploadVo> vos = getFileUploadVos();
            FileUploadVo fuv = vos.get(0);
            InputStream ins = fuv.getInputStream();

            String fileName = getDatePath(userId, BUSINESS_TYPE_DATA_SHARE, FILE_EXT_NAME_PIC);

            // 文件上传
            String uploadResult = null;
            try {
                uploadResult = AppFileUploadUtils.uploadDataSharePic(ins, fileName, userId);
            } catch (IOException e) {
                result.put("success", "false");
                renderText(dataToJson(result));
                return null;
            }

            String picPrefix = AppPropUtil.getPropValue(AppPropUtil.Keys.DOWNLOAD_FILE_HTTP);
            String fullPath = picPrefix + uploadResult;

            result.put("file", fullPath);
            result.put("success", "true");
            renderText(dataToJson(result));
            return null;
        } catch (Exception e) {
            result.put("success", "false");
            renderText(dataToJson(result));
            return null;
        }
    }

    /**
     * 查询用户数据分享页数据
     * 
     * @return String
     */
    private AppDataShareVo findUserShareData(String userId) {
        SysContacts sc = sysContactsIService.findById(userId);

        CallProcedureIService callProcedureIService = SpringContextHolder.getBean(CallProcedureIService.class);
        List<String> params = Arrays.asList(sc.getOldUserId().toString());
        
        long begTime = System.currentTimeMillis();
        List<Map<String, Object>> callProcedureResult = callProcedureIService.getCallProcedureResult(PER_DATA_SHARE,
                params);
        long endTime = System.currentTimeMillis();
        logger.error("---存储过程查询耗时---PER_DATA_SHARE---method out---> {" + (endTime - begTime) + "}");

        AppDataShareVo adsv = new AppDataShareVo();
        adsv.setUserId(userId);
        adsv.setMobile(sc.getMobile());
        
        String webServerUrl = AppPropUtil.getPropValue(AppPropUtil.Keys.DOWNLOAD_FILE_HTTP);
        String dataSharePicPath = AppPropPublicUtil.getPropValue(AppPropPublicUtil.Keys.DEFAULT_DATA_SHARE_PIC_URL);
        adsv.setDataSharePicPath(webServerUrl+dataSharePicPath);
        
        String brokerHeadUrl = AppPropUtil.getPropValue(AppPropUtil.Keys.ZX_BROKER_HEAD_IMG_URL)+sc.getOldUserId();
        adsv.setBreakHeadPath(brokerHeadUrl);
        
        //h5点击分享生成图片时,存在跨域问题,此处转码
        String path = ImageBase64Utils.imageNetToBase64(brokerHeadUrl);
        if (AppStringUtils.isEmpty(path)) {
            String defaultHeadUrl = AppPropPublicUtil.getPropValue(AppPropPublicUtil.Keys.CODE_DEFAULT_HEAD_ICON);
            path = ImageBase64Utils.imageNetToBase64(webServerUrl+defaultHeadUrl);
        }
        adsv.setHeadPicPath("data:image/png;base64,"+path);
        if (CollectionUtils.isNotEmpty(callProcedureResult)) {
            for (Map<String, Object> map : callProcedureResult) {

                if (map.get("PER_ID") != null) {
                    adsv.setPerId(map.get("PER_ID").toString());
                }
                if (map.get("PER_IDCARD") != null) {
                    adsv.setPerIdCard(map.get("PER_IDCARD").toString());
                }
                if (map.get("PER_NAME") != null) {
                    adsv.setPerName(map.get("PER_NAME").toString());
                }
                if (map.get("PER_JOBTIME") != null) {
                    Date pjt = AppDateUtil.parse(map.get("PER_JOBTIME").toString(), AppDatePattern.DATETIME_DEFAULT);
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(pjt);
                    int year = cal.get(Calendar.YEAR);
                    int month = cal.get(Calendar.MONTH) + 1;
                    int day = cal.get(Calendar.DATE);
                    adsv.setPerJobTime(year + "年" + month + "月" + day + "日");
                }
                if (map.get("PER_WORKTIME") != null) {
                    adsv.setPerWorkTime(map.get("PER_WORKTIME").toString());
                }
                if (map.get("CUSTOMERS") != null) {
                    adsv.setCustomers(map.get("CUSTOMERS").toString());
                }
                if (map.get("OWNERS") != null) {
                    adsv.setOwners(map.get("OWNERS").toString());
                }
                if (map.get("SERVICE_OWNERS") != null) {
                    adsv.setServiceOwners(map.get("SERVICE_OWNERS").toString());
                }
                if (map.get("SERVICE_CUSTOMERS") != null) {
                    adsv.setServiceCustomers(map.get("SERVICE_CUSTOMERS").toString());
                }
                //数据处理-与*位伙伴并肩作战>6000的时候,取6000
                if (map.get("COOPERATION") != null) {
                    int con = Integer.valueOf(map.get("COOPERATION").toString());
                    if(con>6000){
                        con=6000;
                    }
                    adsv.setCooperation(String.valueOf(con));
                }
                //数据处理-行政区域>6000的时候,取6000
                if (map.get("AREA_CNT") != null) {
                    int ant = Integer.valueOf(map.get("AREA_CNT").toString());
                    if(ant>6000){
                        ant=6000;
                    }
                    adsv.setAreaCnt(String.valueOf(ant));
                }
                //数据处理-小区>6000的时候,取6000
                if (map.get("PROPERTYINFO_CNT") != null) {
                    int cnt = Integer.valueOf(map.get("PROPERTYINFO_CNT").toString());
                    if(cnt>6000){
                        cnt=6000;
                    }
                    adsv.setPropertyinfoCnt(String.valueOf(cnt));
                }
                //数据处理-关注物业量>6000的时候,取6000
                if (map.get("CONCERNED_PROPERTYINFO") != null) {
                    int pnt = Integer.valueOf(map.get("CONCERNED_PROPERTYINFO").toString());
                    if(pnt>6000){
                        pnt=6000;
                    }
                    adsv.setConcernedPropertyInfo(pnt);
                }
                if (map.get("CONCERNED_HOUSES") != null) {
                    adsv.setConcernedHouses(Integer.parseInt(map.get("CONCERNED_HOUSES").toString()));
                }
                if (map.get("LOOKS") != null) {
                    adsv.setLooks(Integer.parseInt(map.get("LOOKS").toString()));
                }
                if (map.get("BE_LOOKS") != null) {
                    adsv.setBeLooks(Integer.parseInt(map.get("BE_LOOKS").toString()));
                }
                if (map.get("TITLE") != null) {
                    adsv.setTitle(map.get("TITLE").toString());
                }
                if (map.get("CALL_NAME") != null) {
                    adsv.setCallName(map.get("CALL_NAME").toString());
                }
            }
        }
        
        /**
         * 若发生的带看为0,涉及到的行政区和小区也必为0,同时发生的被带看也为0, 不显示数据页2。
         * 若发生的带看为0,且关注物业量和关注房源量任意一个为0,不显示数据页2。
         * 若称号为潜力无限也不显示数据页2
         */
        adsv.setIsShowTwo(AppDataShareVo.IS_SHOW_TWO_YES);
        if (((null==adsv.getLooks() || adsv.getLooks() == 0) && (null==adsv.getBeLooks() || adsv.getBeLooks() == 0)) ||  
            ((null==adsv.getLooks() || adsv.getLooks() == 0) && (null==adsv.getConcernedPropertyInfo() || adsv.getConcernedPropertyInfo() == 0)) ||
            ((null==adsv.getLooks() || adsv.getLooks() == 0) && (null==adsv.getConcernedHouses() || adsv.getConcernedHouses() == 0))||adsv.getTitle().equals("潜力无限")) {
            adsv.setIsShowTwo(AppDataShareVo.IS_SHOW_TWO_NO);
        }
        
        return adsv;
    }

    /**
     * 生成年月日小时文件名称
     * 
     * @param userId       用户Id
     * @param businessType 业务类型
     * @param fileExt      扩展名称
     * @return String
     */
    private String getDatePath(String userId, String businessType, String fileExt) {
        Calendar calendar = Calendar.getInstance();
        int yearInt = calendar.get(Calendar.YEAR);
        int monthInt = calendar.get(Calendar.MONTH) + 1;
        int dayInt = calendar.get(Calendar.DAY_OF_MONTH);
        int hourInt = calendar.get(Calendar.HOUR_OF_DAY);
        String monthStr = monthInt >= 10 ? String.valueOf(monthInt) : "0" + monthInt;
        String dayStr = dayInt >= 10 ? String.valueOf(dayInt) : "0" + dayInt;
        String hourStr = hourInt >= 10 ? String.valueOf(hourInt) : "0" + hourInt;
        return yearInt + monthStr + dayStr + hourStr + "_" + userId + "_" + businessType + fileExt;
    }
    
    /**
     * @param sysContactsIService the sysContactsIService to set
     */
    public void setSysContactsIService(SysContactsIService sysContactsIService) {
        this.sysContactsIService = sysContactsIService;
    }

}

ftl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta content="no-siteapp" http-equiv="Cache-Control">
    <meta content="webkit" name="renderer">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="black" name="apple-mobile-web-app-status-bar-style">
    <!-- uc强制竖屏 -->
    <meta name="screen-orientation" content="portrait">
    <!-- QQ强制竖屏 -->
    <meta name="x5-orientation" content="portrait">
    <title>2019年英雄榜</title>
    <link href="../../lib/agent/css/css.css" rel="stylesheet" >
    <link href="../../lib/agent/css/swiper.min.css" rel="stylesheet" type="text/css"/>
    <link href="../../lib/agent/css/animate.css" rel="stylesheet" >
    <script src="../../lib/agent/js/font.js"></script>
    <script src="../../lib/agent/js/jquery-2.1.3.min.js"></script>
    <script src="../../lib/agent/js/swiper.min.js"></script>
</head>
<body>
<div id="main" class="index">
    <div class="swiper-container">
        <div class="swiper-wrapper">
            <div class="swiper-slide">
                <div class="page page0">
                    <div class="loading">
                    <p>探榜</p>
                        <img class="arrowUp animated fadeOutUp infinite" src="../../lib/agent/images/arrowUp.png" />
                    </div>
                </div>
            </div>
            <div class="swiper-slide">
                <div class="page page1">
                    <div class="page1Wrap">
                        <div class="avatorWrap">
                            <img class="avator" src="${breakHeadPath}" alt="">
                        </div>
                        <p class="name"><span>${perName}</span><label>${callName}</label></p>
                        <div class="agentInfo" style="display: none;">
                            <h3><em style="padding:0;font-size:.36rem;font-weight: bold;">${perJobTime}</em></h3>
                            <p> 是你正式下山的日子,截止到今日,你已在麦田闯荡了<em>${perWorkTime}</em>天。</p>
                            <#switch title> 
                                <#case '潜力无限'>
                                    <p>雨露风霜,朝霞皓月,你不断地向着自己的目标飞奔。每一滴汗水、每一次奔波都将成就你未来的荣耀!我们相信你终将名震江湖!</p>
                                <#break>
                                <#default> 
                                    <p><#if owners != "0" || customers != "0" || serviceOwners != "0" || serviceCustomers != "0">2019年你一路披荆斩棘、行侠仗义,<#if owners != "0" || customers != "0">结识了<#if owners != "0"><em> ${owners}</em>位业主</#if><#if owners != "0" && customers != "0"></#if><#if customers != "0"><em> ${customers}</em>位客户。</#if></#if><#if serviceOwners != "0" || serviceCustomers != "0"><#if serviceOwners != "0">使<em>${serviceOwners}</em>位业主的利益得到保障。</#if><#if serviceCustomers != "0">使<em>${serviceCustomers}</em>位客户的家园梦想得以实现。</#if></#if></#if></p>
                            </#switch>
                        </div>
                        <div class="agentInfo" id="agentInfo"></div>
                    </div>
                    <img class="lightBlue light flash animated infinite" src="../../lib/agent/images/lightBlue.png" alt="">
                    <img class="arrowUp animated fadeOutUp infinite" src="../../lib/agent/images/arrowUp.png" />
                </div>
            </div>
<#if isShowTwo == 1>
    <div class="swiper-slide">
        <div class="page page2">
            <div class="page2Wrap">
                <img class="hanshui" src="../../lib/agent/images/hanshui.png" alt="">
                <div class="toast toast1" style="display: none;">
                    <h6><span>${cooperation}</span></h6>
                    <p><#if cooperation != "0">这一年你与${cooperation}位伙伴并肩作战</#if></p>
                </div>
                <div class="toast toast2" style="display: none;">
                    <h6><span>${concernedHouses}</span></h6>
                    <p><#if areaCnt != "0" || propertyinfoCnt != "0">足迹遍布<#if areaCnt != "0">${areaCnt}个行政区,</#if><#if propertyinfoCnt != "0">${propertyinfoCnt}个小区,</#if></#if><#if concernedPropertyInfo != 0 || concernedHouses != 0>关注<#if concernedPropertyInfo != 0>${concernedPropertyInfo}个物业,</#if><#if concernedHouses != 0>${concernedHouses}套房源</#if></#if></p>
                </div>
                <div class="toast toast3" style="display: none;">
                    <h6><span>${looks+beLooks}</span></h6>
                    <p><#if looks != 0 || beLooks != 0>形成<#if looks != 0>${looks}次带看</#if><#if looks != 0 && beLooks != 0></#if><#if beLooks != 0>${beLooks}次被带看</#if></#if></p>
                </div>
                <div class="toast" id="toast1"><em></em></div>
                <div class="toast" id="toast2"><em></em></div>
                <div class="toast" id="toast3"><em></em></div>
            </div>
            <img class="lightYellow light flash animated infinite" src="../../lib/agent/images/lightYellow.png" alt="">
            <img class="lightYellow2 light flash animated infinite" src="../../lib/agent/images/lightYellow.png" alt="">
            <img class="lightYellowLong light flash animated infinite" src="../../lib/agent/images/lightYellowLong.png" alt="">
            <img class="arrowUp animated fadeOutUp infinite" src="../../lib/agent/images/arrowUp.png" />
        </div>
    </div>
</#if>
            
            <div class="swiper-slide">
                <div class="page page3" id="app">
                    <div class="page3Wrap">
                        <img class="hero" src="../../lib/agent/images/hero.png" alt="">
                        <p class="heroSay">感谢你为维护房产经纪行业的繁荣稳定和蓬勃发展奉献青春与热血!</p>
                        <div class="chenghao">
                            <p class="nihude">你获封</p>
                            <p class="dechenghao">的称号!</p>
                            <div class="honorWrap">
        
<#switch title> 
    <#case '潜力无限'> 
        <img class="honor animated" src="../../lib/agent/images/1.png" alt="">
    <#break> 
    <#case '小有所成'> 
        <img class="honor animated" src="../../lib/agent/images/2.png" alt="">
    <#break> 
    <#case '不同凡响'> 
        <img class="honor animated" src="../../lib/agent/images/3.png" alt="">
    <#break> 
    <#case '人中龙凤'> 
        <img class="honor animated" src="../../lib/agent/images/4.png" alt="">
    <#break> 
    <#case '名震江湖'> 
        <img class="honor animated" src="../../lib/agent/images/5.png" alt="">
    <#break> 
    <#case '一代宗师'> 
        <img class="honor animated" src="../../lib/agent/images/6.png" alt="">
    <#break> 
    <#case '独孤求败'> 
        <img class="honor animated" src="../../lib/agent/images/7.png" alt="">
    <#break> 
    <#default> 
        <img class="honor animated" src="../../lib/agent/images/1.png" alt="">
</#switch>

                            </div>
                        </div>
                        <div class="phoneNum">
                            <p>鸿雁传书<span>${mobile}</span></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div id="music" class="music">
    <audio id="audioTag" src="../../lib/agent/images/music.mp3" ></audio>
    <div class="pgs" style="display: none;">
        <div class="pgs-play" id="progress" style="width: 20%;"></div>
    </div>
    <div class="controls">
        <span class="played-time" style="display: none;">00:00</span>
        <button class="play-pause" id="playPause">
            <span class="icon-btn icon-play"></span>
        </button>
        <span class="audio-time" id="audioTime" style="display: none;">0</span>
    </div>
</div>
<script src="../../lib/agent/js/typing.min.js"></script>
<script src="../../lib/agent/js/qrcode.js"></script>
<script src="../../lib/agent/js/html2canvas.min.js"></script>
<script>
var audio = $('#audioTag').get(0);
var playState = '';
    $('#playPause').click(function(){
        
        //改变暂停/播放icon
        if(audio.paused){
            audio.play();
            $('.icon-btn').removeClass('icon-play').addClass('icon-pause')
        } else{
            audio.pause();
            $('.icon-btn').removeClass('icon-pause').addClass('icon-play')
        }
    })
    audio.addEventListener("pause", function(){ //暂停状态Doing
        playState = false;//暂停状态
    })
    audio.addEventListener("playing", function(){        //播放状态Doing
        playState = true;//播放状态
    });
    document.addEventListener('visibilitychange', function() {
        if(!document.hidden){
            if(playState){
                $('.icon-btn').removeClass('icon-play').addClass('icon-pause');
            }else{
                $('.icon-btn').removeClass('icon-pause').addClass('icon-play')
            }
        }
    })
    //计算发光图层位置大小
    function cmpPosi(){
        var width = window.document.documentElement.getBoundingClientRect().width;
        var scaleNum = width/750;
        $('.page1 .lightBlue').css({'width':width*.208266667,'bottom':scaleNum*432,'right':scaleNum*37});
        $('.page2 .lightYellow').css({'width':width*.152,'bottom':scaleNum*554,'right':scaleNum*150});
        $('.page2 .lightYellow2').css({'width':width*.10533333,'bottom':scaleNum*468,'right':scaleNum*560});
        $('.page2 .lightYellowLong').css({'width':width*.113866667,'bottom':scaleNum*580,'right':scaleNum*372});
        //$('.page2 .toast').css({'width':width*.50533333});
        $('.page2 .toast1,.page2 #toast1').css({'bottom':scaleNum*940,'right':scaleNum*220});
        $('.page2 .toast2,.page2 #toast2').css({'bottom':scaleNum*553,'right':scaleNum*286});
        $('.page2 .toast3,.page2 #toast3').css({'bottom':scaleNum*248,'right':scaleNum*59});
    }
    //设置打字效果
    var typingaAgentInfo = new Typing({
        source: $('.agentInfo').get(0),
        output: document.getElementById('agentInfo'),
        delay: 20
    });
    var typingToast3 = new Typing({
        source: $('.toast3').get(0),
        output: document.getElementById('toast3'),
        delay: 15
    });
    var typingToast2 = new Typing({
        source: $('.toast2').get(0),
        output: document.getElementById('toast2'),
        delay: 15,
        done:function(){
            $('#toast3').addClass('show');
            typingToast3.start()
        }
    });
    var typingToast1 = new Typing({
        source: $('.toast1').get(0),
        output: document.getElementById('toast1'),
        delay: 15,
        done:function(){
            $('#toast2').addClass('show');
            typingToast2.start()
        }
    });
    $(function () {
        //计算发光图层和对话框位置大小
        cmpPosi();
        
        //获取到第二页三段文字的高度并赋值给要打印的div
        $('#toast1').height($('.toast1').eq(0).height());
        $('#toast2').height($('.toast2').eq(0).height());
        $('#toast3').height($('.toast3').eq(0).height());

        //计算要分享的#shareWrapClone的宽高
        var width = $('body').width();
        var height = $('body').height();
        //根据高度计算分享图片的样式
        $('.qrCodeBox').css('height',height*.159);
        $('#shareHonor').css({'height':height*.159,'bottom':height*.159});
        $('#qrcode').width(width*.2);

        //根据宽高比计算相关背景图片的样式
        if(width/height>=414/760){
            $('.hanshui').css({'margin-top':'0','width':'70%','height':'auto'})
            $('.page3Wrap').css({'background-position-y':'bottom'})
            var scaleNum = width/height;
            if(width/height>=414/700 && width/height<375/650){
                $('.page2 .toast1,.page2 #toast1').css({'bottom':scaleNum*750,'right':scaleNum*70}).addClass('leftArrow');
            }else if(width/height>=375/650 && width/height<375/580){
                $('.page2 .toast1,.page2 #toast1').css({'bottom':scaleNum*height*1.08,'right':scaleNum*60}).addClass('leftArrow');
            }else if(width/height>=375/580 && width/height<375/550){
                $('.page2 .toast1,.page2 #toast1').css({'bottom':scaleNum*height*1.05,'right':scaleNum*60}).addClass('leftArrow');
            }else if(width/height>=375/550){
                $('.page2 .toast1,.page2 #toast1').css({'bottom':scaleNum*height*1.02,'right':scaleNum*50}).addClass('leftArrow');
            }
            
        }
        
        $('.swiper-wrapper').on('transitionend',function(){
            if($('.swiper-slide-active').find('.page3').length>0){
                $('.honor').addClass('fadeInBigToSmall');
            }
        })
    })

    //长按计时器
    var timeOutEvent=0;
    var swiper = new Swiper('.swiper-container', {
        direction: 'vertical',
        //noSwiping : true,
        onSlideChangeEnd:function(swiper) {
            if (swiper.activeIndex == 1 && $('#agentInfo').find('h3').length<=0) {
                //开始首屏打字效果
                typingaAgentInfo.start();
            }
            
            <#if isShowTwo == 1>
                if (swiper.activeIndex == 2 && $('.page2Wrap').find('.show').length<=0) {
                    $('#toast1').addClass('show');
                    typingToast1.start();
                }
            </#if>
            
            if(swiper.activeIndex == <#if isShowTwo == 1>3<#else>2</#if> && $('.page3Wrap').find('.fadeInBigToSmall').length<=0){
               $('.honor').addClass('fadeInBigToSmall');
            }
        }
    });
</script>
</body>
</html>

一.FreeMarkerUtil工具类:

Java代码   收藏代码
  1. import com.huaxia.entity.News;  
  2. import com.huaxia.entity.User;  
  3. import freemarker.template.Configuration;  
  4. import freemarker.template.Template;  
  5. import freemarker.template.TemplateException;  
  6.   
  7. import javax.servlet.http.HttpServletRequest;  
  8. import java.io.*;  
  9. import java.util.HashMap;  
  10. import java.util.Locale;  
  11. import java.util.Map;  
  12.   
  13. /** 
  14.  * 创建人: leon 
  15.  * 创建时间: 2014年11月28日 上午10:07:51 
  16.  * 类描述:Freemarker的工具类 
  17.  */  
  18. public class FreemarkerUtil {  
  19.   
  20.     /** 
  21.      * 通过指定的名字获取相应的模板 
  22.      * @param fileName 
  23.      * @return 
  24.      */  
  25.     public Template getTemplate(HttpServletRequest request,String fileName) {  
  26.         try {  
  27.         Configuration cfg = new Configuration();  
  28.         cfg.setOutputEncoding("UTF-8");  
  29.         cfg.setDefaultEncoding("UTF-8");// 编码设置1    
  30.         cfg.setEncoding(Locale.CHINA, "UTF-8");  
  31.         //设定读取ftl模板文件的目录  
  32.         //cfg.setClassForTemplateLoading(this.getClass(), "/template");     //读取src目录下  
  33.         cfg.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/template"); //读取webroot目录下  
  34.         //在模板文件目录中找到名称为name的文件,并加载为模板  
  35.         Template template = cfg.getTemplate(fileName);  
  36.         template.setEncoding("UTF-8");// 编码设置2  
  37.         return template;  
  38.         } catch (IOException e) {  
  39.             e.printStackTrace();  
  40.         }  
  41.         return null;  
  42.     }  
  43.       
  44.     /** 
  45.      * 通过指定的文件目录和文件名生成相应的文件 
  46.      * @param fileDir 
  47.      * @param fileName 
  48.      */  
  49.     public Boolean printToFile(Template template,String fileDir,String fileName,Map<String,Object> root) {  
  50.         boolean done = false;  
  51.         Writer writer = null;  
  52.         try {  
  53.             //判断多级目录是否存在,不存在则一级级创建  
  54.             String[] paths = fileDir.split("\\\\");//注意:此处“\\”是错误的,必须要“\\\\”才能分割字符串  
  55.             String dir = paths[0];  
  56.             for (int i = 1; i < paths.length; i++) {  
  57.                 dir = dir + File.separator + paths[i];  
  58.                 File file=new File(dir.toString());  
  59.                 if (!file.exists()) {  
  60.                     file.mkdir();  
  61.                 }  
  62.             }  
  63.             //创建输出流  
  64.             File file = new File(fileDir +File.separator+ fileName);    
  65.                  
  66.             //设置生成的文件编码为UTF-8     
  67.             //服务器不支持UTF-8格式HTML时候使用ANSI格式HTML文件,即系统默认编码     
  68.             writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));  // 编码设置3  
  69.             //writer = new FileWriter(fileDir +File.separator+ fileName);  
  70.             //输出模板和数据模型都对应的文件  
  71.             template.process(root, writer);  
  72.             done = true;  
  73.         } catch (IOException e) {  
  74.             e.printStackTrace();  
  75.         } catch (TemplateException e) {  
  76.             e.printStackTrace();  
  77.         } finally {  
  78.             try {  
  79.                 if(writer!=null){  
  80.                     writer.close();  
  81.                 }  
  82.             } catch (IOException e) {  
  83.                 e.printStackTrace();  
  84.             }  
  85.         }  
  86.         return done;  
  87.     }  
  88.       
  89.     /** 
  90.      * 通过传入的请求和新闻信息重新生成html文件 
  91.      * @param news  //新闻实体类 
  92.      * @param request   //请求 
  93.      * @param user  //用户 
  94.      * @return 
  95.      */  
  96.     public boolean genenateHtml(News news,HttpServletRequest request,User user) {  
  97.         String fileName = news.getFileName();  
  98.         Map<String, Object> root = new HashMap<String, Object>();  
  99.         root.put("id", news.getId());  
  100.         root.put("title", news.getTitle());  
  101.         root.put("create_date", news.getCreateDate());  
  102.         root.put("creator", news.getCreator());  
  103.         root.put("content", ClobUtil.ClobToString(news.getContent()));  
  104.         root.put("fileName", news.getUploadFile()==null?"":news.getUploadFile());  
  105.         FreemarkerUtil freemarkerUtil = new FreemarkerUtil();  
  106.         Template template = null;  
  107.         template = freemarkerUtil.getTemplate(request, "news.ftl");//新闻发布系统的freemarker模板  
  108.         String htmlDir = news.getDir();  
  109.         boolean done = printToFile(template, htmlDir, fileName, root);  
  110.         return done;  
  111.     }  
  112. }  

猜你喜欢

转载自www.cnblogs.com/pypua/p/12630964.html