页面静态化介绍
当然不是 只是这些网站使用了页面静态化技术
页面静态化好处
1.有利于搜索引擎搜索,搜索引擎在网络上获取页面时,是优先获取html静态页面的2.页面静态化技术也是使用后台处理的,因此,他并没有失去动态页面易于维护的优势
3.有利于网页的性能呵呵安全
页面静态化方法
1.伪静态 顾名思义 并没有将页面转化为静态页面,而是通过URL重写技术,将页面路径重
2.真静态,这种方案真正将动态页面批量转化为静态页面,并储存在服务器上,
这样用户访问静态页面时,该页面真是存在,不需要重定向,但自方法需要提前转化
3.折中法 这种方案是前面两种方案的这种做法,也是使用普遍的做法。当用户请求摸个静态
折中法
折中法处理 思路
1.获取当前请求的URl 截取其中ID2.根据汽车ID 拼接静态页面 判定页面是否存在
3.如果页面不存在 查询汽车信息,替换模版标签,生成静态页面
4.此时静态页面已存在 直接找到静态页面,将其发送至客户端
6.修改文件配置
7.测试
代码实例
namespace ch2
{
public class CarHd : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
//获取请求的原始URl
string strurl = context.Request.RawUrl;
//最后斜杠的位子
int last = strurl.LastIndexOf("_");
//最后点的位置
int dot = strurl.LastIndexOf(".");
//截取信息
int name = int.Parse(strurl.Substring(last + 1, dot - last - 1));
//当前访问的汽车详情页面物理路径
string carPath = context.Server.MapPath("info_" + name + ".html");
//判定当前对应的静态页面是否存在
if (!File.Exists(carPath))
{
//初始化数据
CarList carlist = new CarList();
//静态页面模板路径
string templatePath = context.Server.MapPath("T5.html");
//读取模板
string Temp = ReadTemplate(templatePath);
//替换模板中的标签
Temp = Temp.Replace("{$Name}", carlist.list[name].Name);
Temp = Temp.Replace("{$Brand}", carlist.list[name].Brand);
//保存静态页面
WriteHTML(carPath, Temp);
}
//将静态页面发送至客户端
context.Response.WriteFile(carPath);
}
//读取模板的方法、
private string ReadTemplate(string path) {
//检测文件是否存在
if (!File.Exists(path))
{
//模板文件不存在抛出异常
throw new Exception("错误101");
}
//创建文件流
FileStream fs = new FileStream(path, FileMode.Open);
//创建读取器
StreamReader sr = new StreamReader(fs);
//读取文件流中文本
string html = sr.ReadToEnd();
//关闭读取器
sr.Close();
//关闭文件流
fs.Close();
//返回读取的模版html
return html;
}
//编写静态文件
private void WriteHTML(string path,string html)
{
FileStream fs = new FileStream(path, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.Write(html);
sw.Close();
fs.Close();
}
}
}
namespace ch2
{
public class Car
{
public string Name { get; set; }
public string Brand { get; set; }
}
public class CarList
{
public List<Car> list = new List<Car>() {
new Car() { Name="1",Brand="1"},
new Car() { Name="5",Brand="5"},
new Car() { Name="2",Brand="2"},
new Car() { Name="3",Brand="3"},
new Car() { Name="4",Brand="4"},
};
}
}
<form id="form1" runat="server">
<a href="car/info_1.html">1</a>
<a href="car/info_2.html">2</a>
</form>