由于這段時間比較輕松,于是想到很多的企業(yè)網(wǎng)站,新聞網(wǎng)站需要將頁面靜態(tài)化,于是寫了個封裝類來實現(xiàn)靜態(tài)文件的生成,思路比較簡單,但未完善,網(wǎng)友可根據(jù)自己的思路將此類擴展,運用了簡單工廠模式,先來看看靜態(tài)類的父類:StaticBase(抽象類)
public void Dispose()
{
sw.Dispose();
sr.Dispose();
}
#endregion
}
#region 對應的頁面名稱
/// <summary>
/// 對應的頁面名稱
/// </summary>
public enum FlagsFileName : byte
{
/// <summary>
/// 新聞
/// </summary>
[Description("新聞")]
News = 0,
/// <summary>
/// 頭部
/// </summary>
[Description("頭部")]
head=1,
/// <summary>
/// 腳部
/// </summary>
[Description("腳部")]
foot=2,
}
最后的一個枚舉用于定義不同位置或不同類別的靜態(tài)頁所對應的子類,接下來看看其中一個子類的實現(xiàn)(該子類是用于所有單頁,如數(shù)據(jù)庫中有100條新聞記錄,那相應的生成100個新聞html頁面,格式用模板定義的格式確定)
首先模板文件時靜態(tài)的html頁面,其中所有的需要從數(shù)據(jù)庫中替換的字段用一對$包含,如數(shù)據(jù)庫中的新聞標題字段為titles,則模板頁中相應的標題位置用$titles$表示,頁面如下
$foot$
<!--ft end-->
</body>
</html>
到這里知道個大概了吧,接下來就是這中頁面類型的子類實現(xiàn),我將它的名稱定義為ViewPage,因為所有可以單獨顯示的頁面都可以用這個子類,代碼如下
protected override bool WriteFile()
{
string str = "";
try//從指定模板文件中讀取html代碼
{
sr = new StreamReader(HttpContext.Current.Server.MapPath(PagePath + this.masterhtml), code);
str = sr.ReadToEnd();
}
catch (Exception ex)//異常則指定返回的錯誤信息
{
sr.Close();
sr.Dispose();
this.o_sucess = false;
this.errorstring = ex.Message;
return this.o_sucess;
}
sr.Close();
sr.Dispose();
List<FlagsFileName> fn = new List<FlagsFileName>();
fn.Add(FlagsFileName.head);
fn.Add(FlagsFileName.foot);
PointPage pg = new PointPage(fn, str);
//要保存的文件名稱
string htmlfilename = string.Empty;
string changestring = "";//要更改的字符串
foreach (DataRow row in this.rowlist)//遍歷數(shù)據(jù)源數(shù)組中的每個數(shù)據(jù)表
{
string newString = str;
try
{
htmlfilename = FileName[fname] + "_" + row[thekey].ToString() + ".html";//給文件命名
foreach (DataColumn c in row.Table.Columns)//遍歷單個數(shù)據(jù)表的列名
{
changestring = "$" + c.ColumnName + "$";
newString = newString.Replace(changestring, row[c].ToString());
}
sw = new StreamWriter(HttpContext.Current.Server.MapPath(SavePath + htmlfilename), false, code);
sw.Write(newString);
sw.Flush();
}
catch (Exception ex)
{
this.o_sucess = false;
this.errorstring = ex.Message;
return this.o_sucess;
}
}
sw.Dispose();
sw.Close();
return true;
}
}
好,到這里實現(xiàn)了底層的思路設計,那調用就很簡單了,某個aspx頁面,一個按鈕button,一個點擊事件Button_Click,點擊事件內需要做的就是聲明一個基類StaticBase,將它實例化成一個子類ViewPage,傳遞的參數(shù)為一個數(shù)據(jù)項集合,DataRow[]為從數(shù)據(jù)表中讀取的集合,包含需要替換的字段,如select titles,contens,id from news(從新聞表中獲得標識id,標題,內容),以及類型FlagsFileName.News為前天基類提到過的枚舉類型,為單獨頁面的生成方式,已經(jīng)重命名的標識列,如此處為id,則生成的頁面格式為
news_1.html,news_2.html以此類推,代碼如下
看到這里大家如果再從頭看一遍,相信就能知道靜態(tài)文件的生成的原理了。
新聞熱點
疑難解答