Login.html模板页:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form action="Login.ashx" method="post"> 用户名:<input type="text" name="username" value="{username}" /> 密码:<input type="password" value="{password}" /> <input type="submit" name="btn1" value="提交" /> </form> </body> </html>
Login.ashx:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Web1.Day3; namespace Web1.Day4 { /// <summary> /// Login 的摘要说明 /// </summary> public class Login : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; //1、读取模板页信息 string html = CommonHelper.ReadHtml("~/Day4/Login.html"); //2、根据是否有提交按钮这个name属性,进行判断是否是第一次打开这个页面 string btnLogin=context.Request["btn1"]; //3、判断 if (string.IsNullOrEmpty(btnLogin))//第一次打开这个页面 { //4、读取浏览器上一次关闭服务区端设置给浏览器中的cookie信息 HttpCookie cookiesLastName = context.Request.Cookies["LastUserName"]; //5\ if (cookiesLastName != null) { //6、替换模板页中的用户名占位符 html = html.Replace("{username}", cookiesLastName.Value);//-------------------------这里注意要加上value //---string 变量 = Response.Cookies["名称"].Value; } else { // 7、没有读取到用户名 html = html.Replace("{username}", ""); } //8\输出替换后的模板页 context.Response.Write(html); } else//否则用户点击 提交 按钮,就更要重新设这cookie信息 { //8.从请求报文中读取 string username = context.Request["username"]; string pwd = context.Request["password"];//---------------------------如果设置密码cookis怎么办??再实例化一个cookie??????? //9.实例化一个cookies对象,来设置cook //命名cookie HttpCookie cookLastName = new HttpCookie("LastUserName"); //赋值cookie cookLastName.Value = username; cookLastName.Expires = DateTime.Now.AddDays(7); //将cookie信息保存到报文中 context.Response.SetCookie(cookLastName); //提交成功重定向 context.Response.Redirect("MomeryTest.ashx"); } } public bool IsReusable { get { return false; } } } }