B048-cms03-前端首页文章列表展示 页面静态化

目录

      • 抽取公共资源
        • 抽取导航条和侧边栏
          • 1.新建/WEB-INF/views/common文件夹
          • 2.新建header.jsp和leftMenu.jsp
          • 3.引入Index.jsp和Article.jsp
        • 抽取静态资源
          • 新建topStatic.jsp文件
          • 引入Index.jsp和Article.jsp
          • 新建buttomStatic.jsp
          • 引入Index.jsp和Article.jsp
        • 抽取js文件
          • 在WEB-INF外部/WebContent/static/system/js下新建article文件夹和article.js
          • 引入article.jsp
      • 前台首页展示
        • 前台页面发送请求
        • 后端处理完成
        • 前台页面展示
      • 页面静态化
        • FreeMark入门案例
        • 抽取工具类
        • 模板中加入if判断和list遍历
        • 添加生成静态页面
        • 删除文章前先删除静态页面
        • 更新用新数据生成新html并删除旧html
      • 页面跳转详情信息

抽取公共资源

抽取导航条和侧边栏

1.新建/WEB-INF/views/common文件夹
2.新建header.jsp和leftMenu.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
		<header class="app-header">
    		<a class="app-header__logo" href="index.html">源码时代a>
			<a class="app-sidebar__toggle" href="#" data-toggle="sidebar" aria-label="Hide Sidebar">a>
			
      		<ul class="app-nav">
        		
       	 		<li class="dropdown">
        			<a class="app-nav__item" href="#" data-toggle="dropdown" aria-label="Open Profile Menu">
        			<i class="fa fa-user fa-lg">i>a>
          			<ul class="dropdown-menu settings-menu dropdown-menu-right">
            			<li>
            				<a class="dropdown-item" href="page-login.html">
            				<i class="fa fa-sign-out fa-lg">i> 退出 a>
            			li>
          			ul>
        		li>
      		ul>
		header>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
		<div class="app-sidebar__overlay" data-toggle="sidebar">div>
    	<aside class="app-sidebar">
      		<div class="app-sidebar__user">	
      			<img class="app-sidebar__user-avatar" width="48px" height="48px" src="/static/system/images/m1.jpg" alt="User Image">
        		<div>
          			<p class="app-sidebar__user-name">John Doep>
        		div>
      		div>
      		<ul class="app-menu">
	        	<li>
	        		<a class="app-menu__item active" href="/system/article/index">
	        			<i class="app-menu__icon fa fa-dashboard">i>
	        			<span class="app-menu__label">文章管理span>
	        		a>
	        	li>
      		ul>
		aside>
3.引入Index.jsp和Article.jsp
		<!-- 导航条-->
		<%@ include file="/WEB-INF/views/common/header.jsp" %>
        <!-- 侧边菜单 -->
    	<%@ include file="/WEB-INF/views/common/leftMenu.jsp" %>

抽取静态资源

新建topStatic.jsp文件
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<link rel="stylesheet" type="text/css" href="/static/system/css/main.css">

<link rel="stylesheet" type="text/css" href="/static/system/css/font-awesome.min.css">

<link rel="stylesheet" href="/static/system/gridmanager/css/gm.css">

<script type="text/javascript" src="/static/system/gridmanager/js/gm.js">script>
引入Index.jsp和Article.jsp
		
    	<%@ include file="/WEB-INF/views/common/topStatic.jsp" %>
新建buttomStatic.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<script src="/static/system/js/jquery-3.3.1.min.js">script>
<script type="text/javascript" src="/static/system/js/jquery.jdirk.js">script>
<script type="text/javascript" src="/static/system/js/form-load.js">script>
<script type="text/javascript" src="/static/system/js/jquery-form.js">script>
<script src="/static/system/js/popper.min.js">script>
<script src="/static/system/js/bootstrap.min.js">script>
<script src="/static/system/js/main.js">script>

<script src="/static/system/js/plugins/pace.min.js">script>

<script type="text/javascript" src="/static/system/js/plugins/chart.js">script>
引入Index.jsp和Article.jsp
		
    	<%@include file="/WEB-INF/views/common/buttomStatic.jsp" %>

抽取js文件

在WEB-INF外部/WebContent/static/system/js下新建article文件夹和article.js
document.querySelector('#table-demo-ajaxPageCode').GM({
		        gridManagerName: 'demo-ajaxPageCode',	//名字随意
		        ajaxData: '/system/article/findAll',	//改成findAll
		        ajaxType: 'POST',
		        supportAjaxPage: true,		//是否支持分页
		        sizeData: [5,10,15,20],
		        pageSize: 5,
		        currentPageKey: "localPage",
		        pageSizeKey: "pageSize",
		        supportAdjust: false,
		        supportDrag: false,
		        columnData: [
		            {
		            	key: 'title',
		                align: "center",
		                text: '文章标题'
		            },{
		                key: 'type',
		                align: "center",
		                text: '文章类型',
		                template: function(cell, row, index, key){// 模板   
		                    return cell.name;
		                }
		            },{
		            	key: 'url',
		                align: "center",
		                text: 'url'
		            },{
		                key: 'clickCount',
		                align: "center",
		                text: '点击量'
		            },{
		                key: 'createDate',
		                align: "center",
		                text: '日期'
		            },{
		            	key: 'enable',
		                align: "center",
		                text: '是否启用',
		                template: function(cell, row, index, key){// 模板
		                	//console.debug(cell) // enable属性对应的值
		                	//console.debug(row) // 一行数据的信息  是一个对象
		                	//console.debug(index) // 索引
		                	//console.debug(key) // key对应的字段
		                    return cell?"启用":"禁用";
		                }
		            },{
		                key: 'id',
		                align: "center",
		                text: '操作   添加',
		                template: function(cell, row, index, key){// 模板
		                	// row是一个json对象,要转成string
		                	 var str = JSON.stringify(row);
		                	//  console.debug(str);
		                	// data:  数据必须是标准格式  {'id':10,'name':'zs'}
		                    return '+cell+'" href="javascript:;">删除  '+
		                    	   "修改";
		                }
		            }
		        ]
		    });
		    
		    // 高级查询绑定事件
		    $("#queryButton").click(function(){
		    	
		    	// 获取参数    jquery.jdirk.js提供的方法
		    	var dataForm = $("#queryForm").serializeObject();
		    	
		    	// 发送请求  相当于发送的是gridmanager的url
		    	GridManager.setQuery('demo-ajaxPageCode', dataForm);
		    });
		    
		    
		    var delId;
		 	// 删除操作  绑定的是删除按钮
		    $("body").on("click","a[data-id]",function(){
		    	// 获取id
		    	delId = $(this).data("id");
		    	// alert(delId)
		    	// 弹出模态框
		    	$("#delModal").modal("show");
		    });
		 	
		 	// 删除模态框确定按钮  绑定一个事件  发送删除请求
		    $("#delModalButton").click(function(){
		    	
		    	// alert("......");
		    	// 删除请求
		    	$.ajax({
		    		type: "post",
		    		url: "/system/article/delById",
		    		data: {"id":delId}, // "id="+delId
		    		dataType: "json",
		    		success: function(msg){
		    			if(msg.success){// 成功
		    				// 关闭模态框
		    				$("#delModal").modal("hide");
		    				// 刷新数据 ????
		    				GridManager.refreshGrid("demo-ajaxPageCode", true);
		    			}else{
		    				// 关闭模态框
		    				$("#delModal").modal("hide");
		    				// 失败提示
		    				alert(msg.error)
		    			}
		    		}
		    	});		    	    	
		    });
		 	
		    // 添加操作  绑定添加按钮  事件委托
		    $("body").on("click","#addBtn",function(){
 		    	// 清空form中数据
		    	$("#saveForm").clearForm();
				
		    	// 手动清空隐藏域id
		    	$("#saveId").val("");
		    	
		    	// 弹出模态框
		    	$("#saveModal").modal("show");
		    })
		    
		    // 修改操作  绑定修改按钮  事件委托
		    $("body").on("click","a[data-row]",function(){
		    	// 清空form中数据
		    	$("#saveForm").clearForm();	// clearForm()、ajaxSubmit()都是jquery-form.js插件的方法
		    	// 数据回显  获取数据
		    	var row = $(this).data("row");
		    	// console.debug(row);
		    	
		    	// 数据回显	插件提供的方法
		    	$("#saveForm").setForm(row);
		    	
		    	// 弹出模态框
		    	$("#saveModal").modal("show");
		    })
		    
		    // 保存操作
		    $("#saveButton").click(function(){
		    	// 发送请求
		    	// 把form表单中的数据发送到后台,url路径是form中的action
		    	$("#saveForm").ajaxSubmit({
		    		success: function(msg){	    			
			    		if(msg.success){// 成功
			    			// 关闭模态框
			    			$("#saveModal").modal("hide");
			    			// 刷新数据 ????
			    			GridManager.refreshGrid("demo-ajaxPageCode");
			    		}else{
			    			// 关闭模态框
			    			$("#saveModal").modal("hide");
			    			// 失败提示
			    			alert(msg.error)
			    		}		 
		    		}
		    	});
		    });
引入article.jsp

<script type="text/javascript" src="/static/system/js/article/article.js">script>

前台首页展示

引入页面:复制resource里的home文件夹到工程WebContent目录下

将静态资源文件放到static文件夹中,修改引入路径

前台页面发送请求

							// 查询所有的article
							$.ajax({
								type: "post",
								url: "/home/article/findAll",
								dataType:"json",
								success: function(msg){
									console.debug(msg);
								}							
							});

后端处理完成

新建HomeController

@Controller
@RequestMapping("/home")
public class HomeController {
	
	@Autowired
	private IArticleService service;
	
	/**
	 * @Description:前台查询所有article
	 */
	@RequestMapping("/article/findAll")
	@ResponseBody
	public Map<String, Object> findAll(){
		
		return service.findAll();
		
	}
}

ArticleServiceImpl

	@Override
	public Map<String, Object> findAll() {
		// 三个list  ???
		// 技术文章
		List<Article> list1 = mapper.findArticleByCode("technology");
		// 行业新闻
		List<Article> list2 = mapper.findArticleByCode("industry");
		// 学科咨询
		List<Article> list3 = mapper.findArticleByCode("subject");
		
		Map<String,Object> map = new HashMap<>();
		map.put("technology", list1);
		map.put("industry", list2);
		map.put("subject", list3);
		
		return map;
	}

ArticleMapper

	
	<select id="findArticleByCode" resultType="article">
		select * from t_article t,t_article_type ty where t.typeId=ty.id
		and ty.code = #{Code} and t.`enable`=1 ORDER BY createDate desc
		limit 8
	select>

前台页面展示

<div class="content flex-box">
    <div class="wrapper">
        <div class="sectitle-bar flex-box">
            <div class="sectitle">技术文章div>
            <a target="_blank" href=""  class="more">更多a>
        div>
        <ul id="technology">
            
            
        ul>
    div>
    <div class="wrapper">
        <div class="sectitle-bar flex-box">
            <div class="sectitle">行业新闻div>
            <a target="_blank" href=""  class="more">更多a>
        div>
        <ul id="industry">
            
            
        ul>
    div>
    <div class="wrapper">
        <div class="sectitle-bar flex-box">
            <div class="sectitle">学科资讯div>
            <a target="_blank" href=""  class="more">更多a>
        div>
        <ul id="subject">
            
            
        ul>
    div>
div>
// 查询所有的article
$.ajax({
    type: "post",
    url: "/home/article/findAll",
    dataType:"json",
    success: function(msg){
        // console.debug(msg);
        $.each(msg.technology,function(){// 技术文章  url title createDate
            var a = '+this.url+'">
  • +this.title+'">
    '+this.createDate+'
  • ' $("#technology").append(a); }); $.each(msg.industry,function(){// 行业新闻 var a = '+this.url+'">
  • +this.title+'">
    '+this.createDate+'
  • ' $("#industry").append(a); }); $.each(msg.subject,function(){// 学科咨询 var a = '+this.url+'">
  • +this.title+'">
    '+this.createDate+'
  • ' $("#subject").append(a); }); } });

    cms:两套前端系统对应同一套后端系统,后台改变数据库内容,前台获取展示被后台改变后的数据库内容

    web.xml中配置前端欢迎界面可省略部分后缀直接访问前台首页

    	<welcome-file-list>
    		<welcome-file>home/index.htmlwelcome-file>
    	welcome-file-list>
    

    页面静态化

    FreeMark入门案例

    /src/test/java/下新建FreeMarkerTest

    public class FreeMarkerTest {
    	
    	@Test
    	public void testName() throws Exception {
    //		1.导入freemarker.jar
    //		2.获取模板(Template)对象
    //			获取Configuration对象 -- 为了获取模板对象
    		Configuration config = new Configuration(Configuration.VERSION_2_3_28);
    //			设置默认加载路径
    		File file = new File("D:/WorkspaceOfEclipse/cms03/src/main/WebContent/static/template");
    		config.setDirectoryForTemplateLoading(file);
    //			设置默认编码
    		config.setDefaultEncoding("utf-8");
    //			获取模板
    		Template template = config.getTemplate("test.ftl");
    //		3.准备数据
    //			map
    		HashMap<String, Object> map = new HashMap<>();
    		map.put("name", "tom");
    		map.put("age", 20);
    //			java实体对象
    //		4.template.process()生成静态资源
    		String url = System.currentTimeMillis()+".html";
    		FileWriter out = new FileWriter(new File(file, url));
    		template.process(map, out);
    	}
    
    }
    

    /WebContent/static/下新建template文件夹放入test.ftl模板

    DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title heretitle>
    head>
    <body>
    	<h1>${name}h1>
    body>
    html>
    

    运行看结果

    抽取工具类

    FreeMarkerUtil

    public class FreeMarkerUtil {
    
    	/**
    	 * @Description:(作用) 静态资源模板
    	 * @param:@param templatePath : 模板路径
    	 * @param:@param name   :  模板名称
    	 * @param:@param data   : 数据
    	 * @param:@param suffix : 后缀
    	 * @param:@return :    url
    	 */
    	public static String createFile(String templatePath,String name,Object data,String suffix){
    		FileWriter out = null;		
    		try {
    //			1.导入freemarker.jar
    //			2.获取模板(Template)对象
    //				获取Configuration对象 -- 为了获取模板对象
    			Configuration config = new Configuration(Configuration.VERSION_2_3_28);
    //				设置默认加载路径
    			File file = new File(templatePath);
    			config.setDirectoryForTemplateLoading(file);
    //				设置默认编码
    			config.setDefaultEncoding("utf-8");
    //				获取模板
    			Template template = config.getTemplate(name);
    //			3.准备数据
    //			4.template.process()生成静态资源
    			String url = System.currentTimeMillis()+suffix;
    			out = new FileWriter(new File(file, url));
    			template.process(data, out);
    			// 返回一个url
    			return url;
    		} catch (Exception e) {
    			// TODO: handle exception
    		}finally {
    			if(out!=null){
    				try {
    					out.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    		}
    		return null;
    	}
    }
    

    测试

    	@Test
    	public void test1() throws Exception {
    		String path = "D:/WorkspaceOfEclipse/cms03/src/main/WebContent/static/template";
    		ArticleType type = new ArticleType(3L, "人文关怀", "person");
    		
    		FreeMarkerUtil.createFile(path, "test.ftl", type, ".html");
    	}
    

    模板中加入if判断和list遍历

    FreeMarkerTest

    	@Test
    	public void test1() throws Exception {
    		String path = "D:/WorkspaceOfEclipse/cms03/src/main/WebContent/static/template";
    		
    		//ArticleType type = new ArticleType(3L, "人文关怀", "person");
    		
    		HashMap<String, Object> map = new HashMap<>();
    		map.put("name", "tom");
    		map.put("age", 16);
    		
    		List<String> list = new ArrayList<String>();
    		list.add("霸王洗发水");
    		list.add("返现1000元");
    		map.put("lists", list);
    		FreeMarkerUtil.createFile(path, "test.ftl", map, ".html");
    	}
    

    test.ftl

    DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title heretitle>
    head>
    <body>
    	<#if age lt 18>
    		未成年
    		<#else>
    		成年了	
    	#if>
            
        <#list lists as list>
    		${list}
    	#list>	
    body>
    html>
    

    添加生成静态页面

    后台点击添加生成静态页面,前台点击后直接进入已生成的页面

    1.将article.html改成article.ftl模板

    <div class="info">
        <span><span b>分类: span>视频教程span><span><span b>浏览: span>${clickCount}span>
    div>
    <div class="title">${title}div>
    <div class="content">
        ${content}
    div>
    

    2.后台添加文章方法加入生成页面逻辑
    ArticleServiceImpl

    	@Override
    	public void add(Article article,HttpServletRequest req) {
    		// 获取路径
    		String templatePath = req.getServletContext().getRealPath("/static/template");
    		// 判断file是否存在,如果不存在,就创建一个
    		File file = new File(templatePath);
    		if(!file.exists()){
    			// 创建一个
    			file.mkdirs();
    		}		
    		// 生成页面html
    		String url = FreeMarkerUtil.createFile(templatePath, "article.ftl", article, ".html");
    		// 把urlset到article中
    		article.setUrl(url);
    		mapper.add(article);
    	}
    

    3.访问测试
    http://localhost/static/template/1687172260785.html

    删除文章前先删除静态页面

    ArticleServiceImpl

    	@Override
    	public void delById(Long id,HttpServletRequest req) {
    		// 删除数据库信息和html文件
    		// 先删除html, 再删除数据库
    		// 获取路径
    		String templatePath = req.getServletContext().getRealPath("/static/template");
    		// 获取url
    		Article dbarticle = mapper.findOne(id);
    		String url = dbarticle.getUrl();
    		
    		// 删除数据库信息
    		mapper.delById(id);
    		// 删除html文件
    		File file = new File(templatePath, url);
    		if(file.exists()){
    			// 存在就删除
    			file.delete();
    		}
    	}
    

    ArticleMapper.xml

    	
    	<select id="findOne" resultType="article">
    		select * from t_article where id = #{id}
    	select>
    

    更新用新数据生成新html并删除旧html

    ArticleServiceImpl

    	@Override
    	public void update(Article article,HttpServletRequest req) {
    		// 生成一个新的html文件
    		// 获取路径
    		String templatePath = req.getServletContext().getRealPath("/static/template");
    		// 判断file是否存在,如果不存在,就创建一个
    		File file = new File(templatePath);
    		if(!file.exists()){
    			// 创建一个
    			file.mkdirs();
    		}		
    		// 生成页面html
    		String url = FreeMarkerUtil.createFile(templatePath, "article.ftl", article, ".html");
    		// 把urlset到article中
    		article.setUrl(url);
    				
    		// 删除之前的html文件   获取修改之前的url
    		Article dbArticle = mapper.findOne(article.getId());
    		
    		// 更新数据库
    		mapper.update(article);	
    		
    		String dburl = dbArticle.getUrl();
    		// 删除  html
    		File file2 = new File(templatePath, dburl);
    		if(file2.exists()){
    			file2.delete();
    		}	
    	}
    

    页面跳转详情信息

    // 查询所有的article
    $.ajax({
        type: "post",
        url: "/home/article/findAll",
        dataType:"json",
        success: function(msg){
            // console.debug(msg);
            $.each(msg.technology,function(){// 技术文章  url title createDate
                var a = '+this.url+'">
  • +this.title+'">
    '+this.createDate+'
  • ' $("#technology").append(a); }); $.each(msg.industry,function(){// 行业新闻 var a = '+this.url+'">
  • +this.title+'">
    '+this.createDate+'
  • ' $("#industry").append(a); }); $.each(msg.subject,function(){// 学科咨询 var a = '+this.url+'">
  • +this.title+'">
    '+this.createDate+'
  • ' $("#subject").append(a); }); } });

    你可能感兴趣的:(笔记总结,前端,java,eclipse,javascript,jquery)