使用Thymeleaf生成html页面

1.引入Maven依赖

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
2.模板页面上代码
<!DOCTYPE html>
<html lang="zh-CN" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>首页</title>

    <link rel="stylesheet" type="text/css"
          href="./static/css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="./static/css/style.css" />
    <link rel="stylesheet" type="text/css"
          href="./static/css/font-awesome.min.css" />
    <link rel="stylesheet" type="text/css" href="./static/css/site.min.css" />
</head>
<body class="nav-fixed">
<div class="page-wrap">
    <header class="site-header" style="padding-top: 0;">
        <nav class="navbar navbar-static-top main-navbar" id="top"
             style="padding: 0 15px;">
            <div class="">
                <div class="navbar-header">
                    <a href="javascript:;" class="navbar-brand brand-bootcdn"><img
                            src="./static/images/logo.png" /></a>
                </div>
            </div>
        </nav>
        <div class="container ">
            <div class="row">
                <div class="col-xs-12">
                    <div class="headLeft">
                        <img src="./static/images/banner.png" />
                    </div>
                    <div class="headRight">
                        <h2 th:text="${site.name}">
                        </h2>
                         <span th:text="${site.version}" style="font-size: 16px;">v1</span>
                        <p th:text="${site.description}">由*****提供全方位的技术支持,用户可与当地的****办事处联系,也可以直接与公司总部客服中心联系
                        </p>
                    </div>
                    <div class="search-wraper" role="search" style="display: none">
                        <div class="form-group">
                            <input class="form-control search clearable"
                                   placeholder="搜索开源库,例如:jquery" autocomplete="off" autofocus=""
                                   tabindex="0" autocorrect="off" autocapitalize="off"
                                   spellcheck="false" /> <i class="fa fa-search"></i>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </header>
    <main id="homeContent" class="packages-list-container"
          style=" position: relative;z-index: 5;margin-top: -40px;">
        <div class="container ">
            <div class="help-index clearfix row"
                 th:unless="${#lists.isEmpty(columnLists)}">
                <div class="help-index-cell col-xs-4"
                     th:each="column : ${columnLists}">
                    <div class="help-index-cell-icon">
                        <!-- <i th:class="|fa ${column.column.icon}|"></i> -->
                        <img th:src="@{'~'+'/static/images/'+${column.column.icon}}"/>
                    </div>
                    <div class="help-index-cell-content">
                        <h2 th:text="${column.column.name}">一级栏目</h2>
                        <ul class="help-common-nav-list show" th:unless="${#lists.isEmpty(column.subColumn)}">
                            <li th:each="subColumn : ${column.subColumn}"><a th:href="@{'~/'+${column.column.path}}" th:text="${subColumn.name}"></a></li>
                        </ul>
                        <div class="help-common-nav-list-more" th:if="${#lists.size(column.subColumn)} gt 3">
                            <a href="javascript:;">更多<i class="fa fa-angle-down"></i></a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
    <footer id="footer" class="footer hidden-print">
        <div class="copy-right">
            <span>COPYRIGHT</span> <span th:text="${site.copyright}">©2018********公司</span>
        </div>
    </footer>
</div>
<script type="text/javascript" src="./static/js/jquery.min.js"></script>
<script type="text/javascript" src="./static/js/bootstrap.min.js"></script>
<script>
    $('.help-common-nav-list-more').click(function () {
        $(this).find("a").toggleClass("show");
        var n = $(this).siblings(".help-common-nav-list");
        n.hasClass("show") ? ($(this).find("a").html('收起 <i class="fa fa-angle-up"></i>'), n.removeClass("show"), n[0].style.height = 40 * n.children("li").length + "px") : ($(this).find("a").html('更多 <i class="fa fa-angle-down"></i>'), n.addClass("show"), n[0].style.height = "122px")
    })
    $(function(){
        var screenHeight = $(window).height();// 窗口高度
        $("#homeContent").css('min-height',screenHeight-175)
$(window).resize(function(){
    var screenHeight = $(window).height();// 窗口高度
    $("#homeContent").css('min-height',screenHeight-175)
})
    })
</script>
</body>
</html>
View Code

3.后台写法

  1 package com.datangmobile.enet.biz.onlinedoc.modular.publish.service.impl;
  2 
  3 import java.io.File;
  4 import java.io.IOException;
  5 import java.util.ArrayList;
  6 import java.util.List;
  7 import java.util.Map;
  8 
  9 import org.apache.commons.collections.CollectionUtils;
 10 import org.apache.commons.io.FileUtils;
 11 import org.springframework.beans.factory.annotation.Autowired;
 12 import org.springframework.stereotype.Service;
 13 import org.springframework.util.ResourceUtils;
 14 import org.thymeleaf.TemplateEngine;
 15 import org.thymeleaf.context.Context;
 16 
 17 import com.alibaba.fastjson.JSON;
 18 import com.datangmobile.enet.biz.core.node.ZTreeNode;
 19 import com.datangmobile.enet.biz.onlinedoc.common.exception.BizOnlineDocExceptionEnum;
 20 import com.datangmobile.enet.biz.onlinedoc.common.exception.BusinessOnlineDocException;
 21 import com.datangmobile.enet.biz.onlinedoc.common.util.ThymeleafUtil;
 22 import com.datangmobile.enet.biz.onlinedoc.modular.document.service.IColumnService;
 23 import com.datangmobile.enet.biz.onlinedoc.modular.document.service.IContentService;
 24 import com.datangmobile.enet.biz.onlinedoc.modular.document.service.ISiteService;
 25 import com.datangmobile.enet.biz.onlinedoc.modular.document.service.ISubColumnService;
 26 import com.datangmobile.enet.biz.onlinedoc.modular.document.service.ISubjectService;
 27 import com.datangmobile.enet.biz.onlinedoc.modular.persistence.model.Column;
 28 import com.datangmobile.enet.biz.onlinedoc.modular.persistence.model.Content;
 29 import com.datangmobile.enet.biz.onlinedoc.modular.persistence.model.Site;
 30 import com.datangmobile.enet.biz.onlinedoc.modular.persistence.model.SubColumn;
 31 import com.datangmobile.enet.biz.onlinedoc.modular.persistence.model.SubColumnAndContentDTO;
 32 import com.datangmobile.enet.biz.onlinedoc.modular.publish.service.IPublishService;
 33 import com.datangmobile.enet.biz.onlinedoc.modular.transfer.ColumnAndSubColumnDTO;
 34 import com.datangmobile.enet.biz.onlinedoc.modular.transfer.SubjectAndContentDTO;
 35 import com.google.common.collect.Lists;
 36 import com.google.common.collect.Maps;
 37 
 38 /**
 39  * @version 1.0.0, 2018年10月25日
 40  * @ClassName: PublishServiceImpl
 41  * @Description: 生成首页文档服务类实现
 42  * @since Siot v0.0.1
 43  */
 44 @Service
 45 public class PublishServiceImpl implements IPublishService
 46 {
 47 
 48     /**
 49      * 模板引擎
 50      */
 51     @Autowired
 52     private TemplateEngine templateEngine;
 53 
 54     @Autowired
 55     private IPublishService publishService;
 56 
 57     @Autowired
 58     private ISiteService siteService;
 59 
 60     /**
 61      * 栏目服务
 62      */
 63     @Autowired
 64     private IColumnService columnService;
 65 
 66     @Autowired
 67     private ISubjectService subjectService;
 68 
 69     @Autowired
 70     private ISubColumnService subColumnService;
 71 
 72     @Autowired
 73     private IContentService contentService;
 74 
 75     /**
 76      * @param siteId @return @see
 77      *            com.datangmobile.enet.biz.onlinedoc.modular.publish.service.IPublishService#indexPublish(java.lang.Integer) @exception
 78      */
 79 
 80     @Override
 81     public Object indexPublish(Integer siteId)
 82     {
 83         // 栏目和一级子栏目
 84         List<ColumnAndSubColumnDTO> columnLists = columnService.listColumnAndChildSubColumn(siteId);
 85         // 专题
 86         List<SubjectAndContentDTO> subjectAndContentList = subjectService.selectSubjectAndContentList();
 87         // 站点
 88         Site site = siteService.selectSiteByOrgCode(siteId);
 89         try
 90         {
 91             Map<String, Object> dataMap = Maps.newHashMap();
 92             dataMap.put("columnLists", columnLists);
 93             dataMap.put("site", site);
 94             dataMap.put("subjectAndContentList", subjectAndContentList);
 95             Context ctx = ThymeleafUtil.getContext(dataMap);
 96             File file = ResourceUtils.getFile("classpath:templates/default");
 97             FileUtils.writeStringToFile(new File(file.getPath() + File.separator + "index.html"),
 98                     templateEngine.process("default/index_tpl", ctx), "UTF-8");
 99 
100             // 子模块页面生成
101             for (ColumnAndSubColumnDTO columnList : columnLists)
102             {
103                 List<SubColumnAndContentDTO> subColumnAndContentList = new ArrayList<>();
104                 Column column = columnList.getColumn();
105                 // 根据主栏目id查询主栏目下的树
106                 List<ZTreeNode> subColumnTree = subColumnService.getSubColumnTree(column.getId());
107                 // 查询栏目下的一级子模块的快捷显示的
108                 List<SubColumn> shortcut = subColumnService.getShortcut(column.getId());
109                 // 把一级子模块快捷显示的和一级子栏目下的内容封装一个dto
110                 // 查询该快捷显示的一级子栏目下的内容
111                 List<Content> contentsList = null;
112                 for (int i = 0; i < shortcut.size(); i++)
113                 {
114                     contentsList = new ArrayList<>();
115                     SubColumnAndContentDTO subColumnAndContent = new SubColumnAndContentDTO();
116                     subColumnAndContent.setSubColumn(shortcut.get(i));
117                     // 下策 根据子栏目id 递归 查询下面是否有叶子没有根据id = 内容表sub_id查询内容表
118                     List<Integer> leafColumnIds = Lists.newArrayList();
119                     recursiveSelectSubColumn(shortcut.get(i).getId(), leafColumnIds);
120                     for (Integer leafColumnId : leafColumnIds)
121                     {
122                         List<Content> contentList = contentService.selectListContent(leafColumnId);
123                         contentsList.addAll(contentList);
124                     }
125                     subColumnAndContent.setContentList(contentsList);
126                     subColumnAndContentList.add(subColumnAndContent);
127                 }
128                 String subColumnTreeJsonString = JSON.toJSONString(subColumnTree);
129                 dataMap.put("subColumnTreeJsonString", subColumnTreeJsonString);
130                 dataMap.put("column", column);
131                 dataMap.put("subColumnAndContentList", subColumnAndContentList);
132                 ctx = ThymeleafUtil.getContext(dataMap);
133                 FileUtils.writeStringToFile(new File(file.getPath() + File.separator + column.getPath()),
134                         templateEngine.process("default/column_tpl", ctx), "UTF-8");
135                 // 根据主栏目id查询叶子节点
136                  selectContentByColumnId(column,dataMap,file,ctx); 
137             }
138 
139         }
140         catch (Exception e)
141         {
142             throw new BusinessOnlineDocException(BizOnlineDocExceptionEnum.INDEX_PUBLISH_EXCEPTION);
143         }
144         return null;
145     }
146 
147     /**
148      * 
149      * @Title: selectContentByColumnId 
150      * @Description: 根据主栏目id查询叶子节点 
151      * @param column
152      * @param dataMap
153      * @param file
154      * @param ctx        
155      * @throws  
156      * @author liduo
157      */
158 
159     private void selectContentByColumnId(Column column, Map<String, Object> dataMap, File file, Context ctx)
160     {
161         List<SubColumn> leafSubColumns = subColumnService.selectMastLevel(column.getId());
162         //主栏目下的内容集合
163         ArrayList<Content> allContentList = Lists.newArrayList();
164         for (SubColumn leafSubColumn : leafSubColumns)
165         {
166             List<Content> contentList = contentService.selectListContent(leafSubColumn.getId());
167             if (CollectionUtils.isNotEmpty(contentList))
168             {
169                     allContentList.addAll(contentList);
170             }
171         }
172         //生成内容页面
173         for (int i = 0; i < allContentList.size(); i++)
174         {
175             if(allContentList.size()>=2) {
176                 if (i == 0)
177                 {
178                     List<Content> newList = allContentList.subList(i, i + 2);
179                     // 上一页
180                     dataMap.put("previousPage", null);
181                     // 下一页
182                     dataMap.put("nextPage", newList.get(1));
183                 }
184                 else if (i == allContentList.size()-1)
185                 {
186                     List<Content> newList = allContentList.subList(i - 1, i);
187                     // 上一页
188                     dataMap.put("previousPage", newList.get(0));
189                     // 下一页
190                     dataMap.put("nextPage", null);
191                 }
192                 else
193                 {
194                         List<Content> newList = allContentList.subList(i-1, i+1);
195                         List<Content> newpreviousPage = allContentList.subList(i, allContentList.size());
196                         // 下一页
197                         dataMap.put("nextPage", newpreviousPage.get(1));
198                         // 上一页
199                         dataMap.put("previousPage", newList.get(0));
200                     
201                 } 
202             }else {
203                 // 下一页
204                 dataMap.put("nextPage", null);
205                 // 上一页
206                 dataMap.put("previousPage", null);
207             }
208             
209             dataMap.put("content", allContentList.get(i));
210             ctx = ThymeleafUtil.getContext(dataMap);
211             try
212             {
213                 FileUtils.writeStringToFile(
214                         new File(file.getPath() + File.separator + allContentList.get(i).getPath()),
215                         templateEngine.process("default/content_tpl", ctx), "UTF-8");
216             }
217             catch (IOException e)
218             {
219                 
220                 throw new BusinessOnlineDocException(BizOnlineDocExceptionEnum.INDEX_PUBLISH_EXCEPTION);
221             }
222         }
223     }
224 
225     /**
226      * @Title: recursiveSelectSubColumn
227      * @Description: 递归查询返回该pid下的所有叶子节点
228      * @param pid
229      * @throws @author liduo
230      */
231     public void recursiveSelectSubColumn(Integer pid, List<Integer> leafColumnIds)
232     {
233         List<SubColumn> subColumnList = subColumnService.selectSubColumnListByPidAndLever(pid);
234         if (CollectionUtils.isNotEmpty(subColumnList))
235         {
236             subColumnList.forEach(subColumn -> {
237                 recursiveSelectSubColumn(subColumn.getId(), leafColumnIds);
238             });
239         }
240         else
241         {
242             leafColumnIds.add(pid);
243         }
244     }
245 
246 }
View Code

以上为部分代码,如有不懂可评论留言,第一时间回复。



posted @ 2019-07-05 17:34  凄凄惨惨戚戚  阅读(7157)  评论(1编辑  收藏  举报