一个简单的生成静态页的方法

来源:互联网 发布:淘宝女士防晒帽 编辑:程序博客网 时间:2024/06/06 00:58

如有不明白的地方欢迎加QQ群14670545 探讨

完整的静态页生成方法是比较复杂的,一般的cms里面都有,正则处理,规则验证,特殊字符的替换,url路径的判断等等,此处我们大部分都略去,只把一个大题的模子呈现出来,具体的细节大家可以自行完善的。

生成静态页的原理是都有一个统一的模板规范,这是必须的,至少在一定的逻辑判断下应该有一个模板。

动手前我们需要建立几个文件:

1.配置文件

2.模板文件

3.基础页面

4.生成静态页的处理类

好的,开始动工:

新建一个TemplatePage.htm模板页面,简单的写入一些东西,如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head>     <title>生成静态页简单示例</title></head><body>    <h1>$ccJon[0]$</h1>    <ul>        <li>页标题:$ccJon[0]$</li>        <li>名称:$ccJon[1]$</li>        <li>网址:<a href="$Porschev[2]$" target="_blank">$ccJon[2]$</a></li>        <li>时间:$ccJon[3]$</li>        <li>详述:$ccJon[4]$</li>    </ul></body></html>
这里的$ccjon[N]$标签是我们需要进行替换的地方,这里写的简单咯,有些cms里面比较纷繁,比如什么for标签(用来循环处理某一个html段的,可能写成loop吐舌头),比如什么ds标签(数据集的处理,当然dt,dr标签一样类似)等等,这里说过,我们做简单的,复杂的东西都是在简单的原理基础上进行一定的业务处理。不说了,go

下面我们来新建一个配置文件,新建文件夹Config,在此文件夹下新建CreateHtml.config配置文件,它的代码如下:

<?xml version="1.0" encoding="utf-8" ?><web>  <website key="0" value="title"/>  <website key="1" value="name"/>  <website key="2" value="url"/>  <website key="3" value="createDate"/>  <website key="4" value="desc"/></web>
这就是个简单的xml格式,一般cms里面有具体的正则和丰富的标签属性及url,这里写的简单,记住原理都一样。

好了,新建一个页面Default.aspx,然后我们放上一个button来把我们的模板页面生成静态页(里面的标签替换成对应内容的),Default.aspx的页面代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MyWebSiteTest.Manager.Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head id="Head1" runat="server">    <title>我的系统平台</title>    <style type="text/css">        a{star: expression(this.onFocus=this.blur());}/*去掉链接的虚线框*/                  p{ font-family:Arial,微软雅黑;}    </style> </head><body style="overflow:hidden;" scroll="no">    <form id="form1" runat="server">        <%= (Session["createnewpath"] != null && Session["createnewpath"].ToString() != "") ?                "<div><p>上次生成的文件路径:<a target=\"_blank\" href=\""                 + Session["createnewpath"].ToString().Replace("~", "..") + "\">"                            + Session["createnewpath"].ToString() + "</a></p></div>" : ""%>        <div>            <asp:Button runat="server" ID="btnCreateHtmlPage" Text="生成静态页" onclick="btnCreateHtmlPage_Click"/>        </div>    </form></body></html>
Session["createnewpath"] 是我用来存储生成的静态页的路径,这里方便我们直观感受

下面我们先不急着写Default.aspx的后台文件代码,先把我们处理生成静态页的类写好:

新建类CreateHtmlBLL.cs,代码如下

using System;using System.IO;using System.Text;using System.Xml;namespace MyWebSiteTest{    public class CreateHtmlBLL    {        #region##读取配置文件某节点的个数        ///<summary>        /// 读取配置文件某节点的个数        ///</summary>        ///<param name="path">配置文件的路径</param>        ///<param name="nodeName">要获取的节点</param>        ///<returns>返回节点个数</returns>        private int ReadConfig(string path, string nodeName)        {            string absoPath = string.Empty;  //绝对路径            try            {                absoPath = System.Web.HttpContext.Current.Server.MapPath(path);                XmlDocument xd = new XmlDocument();                xd.Load(absoPath);                XmlNodeList nodeList = xd.SelectNodes(nodeName);  //得到相应节点的集合                return nodeList.Count;            }            catch (Exception ex)            {                throw new Exception(ex.Message);            }        }        #endregion        #region##创建文件夹        ///<summary>        /// 创建文件夹        ///</summary>        ///<param name="path">要创建的路径</param>        public void CreatFolder(string path)        {            string absoPath = string.Empty;  //绝对路径            try            {                absoPath = System.Web.HttpContext.Current.Server.MapPath(path);                if (!Directory.Exists(absoPath))                {                    Directory.CreateDirectory(absoPath);                }            }            catch (Exception ex)            {                throw new Exception(ex.Message);            }        }        #endregion        #region##生成HTML页        ///<summary>        /// 生成HTML页        ///</summary>        ///<param name="configPath">配置文件的路径</param>        ///<param name="configNodeName">配置文件节点名</param>        ///<param name="temPath">模版页路径</param>        ///<param name="arr">替换数组</param>        ///<param name="createPath">生成HTML路径</param>        public void CreateHtml(string configPath, String configNodeName, string temPath, string[] arr, string createPath, out string createpage)        {            string fileName = string.Empty;         //生成文件名            string absoCrePath = string.Empty;      //生成页绝对路径            string absoTemPath = string.Empty;      //模版页的绝对路径            int nodeCount = 0;                      //节点数            try            {                absoCrePath = System.Web.HttpContext.Current.Server.MapPath(createPath);                absoTemPath = System.Web.HttpContext.Current.Server.MapPath(temPath);                nodeCount = ReadConfig(configPath, configNodeName);                FileStream fs = File.Open(absoTemPath, FileMode.Open, FileAccess.Read);  //读取模版页                StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("utf-8"));                StringBuilder sb = new StringBuilder(sr.ReadToEnd());                sr.Close();                sr.Dispose();                for (int i = 0; i < nodeCount; i++)                {                    sb.Replace("$ccJon[" + i + "]$", arr[i]);                }                CreatFolder("~/" + createPath);                fileName = DateTime.Now.ToFileTime().ToString() + ".html";  //设置文件名(这里可以根据需要变化命名)                //fileName += Guid.NewGuid().ToString();                createpage = createPath + "/" + fileName;                FileStream cfs = File.Create(absoCrePath + "/" + fileName);                StreamWriter sw = new StreamWriter(cfs, Encoding.GetEncoding("utf-8"));                sw.Write(sb.ToString());                sw.Flush();                sw.Close();                sw.Dispose();            }            catch (Exception ex)            {                throw new Exception(ex.Message);            }        }        #endregion    }}

OK,具体的看注释,其实就是一个读取xml文件,然后读取页面内容进行标签替换,下面回到Default.aspx页面,我们写它的后台代码:

public partial class Default : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            if (IsPostBack)                Session.Remove("createnewpath");        }        /// <summary>        /// 生成静态页        /// </summary>        protected void btnCreateHtmlPage_Click(object sender, EventArgs e)        {            try            {                string backurl = string.Empty;                string[] arr = new string[5];                arr[0] = "Porschev 静态页测式";                arr[1] = "jontest";                arr[2] = "http://www.baidu.com";                arr[3] = DateTime.Now.ToString();                arr[4] = "上班时间上CSDN,都是不好好工作的闲人。。。";                MyWebSiteTest.CreateHtmlBLL chb = new CreateHtmlBLL();                chb.CreateHtml("~/Config/CreateHtml.config", "web/website", "~/TemplatePage.htm", arr, "/Topics", out backurl);                Session["createnewpath"] = backurl;                //Response.Redirect(backurl);                //Response.Write("<script type=\"text/javascript\">window.open(\"" + backurl.Replace("~", "..") + "\");</script>");                Response.Redirect(Request.RawUrl);            }            catch (Exception ex)            {                throw new Exception(ex.Message);            }        }    }
到此结束,是不是在Topics文件夹下生成了静态页了呢,自己试验下吧

原创粉丝点击