一個簡單的產生靜態頁的方法

來源:互聯網
上載者:User

如有不明白的地方歡迎加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檔案夾下產生了靜態頁了呢,自己實驗下吧

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.