這個項目整體采用代碼生成器生成,具體看下圖:
一、實現登錄的思路:
1.添加系統CSS和JS
2.構建登錄的Login.aspx的頁面HTML
3.編寫登錄Ext.js的代碼
4.編寫CSS 實現登錄與密碼框前的小圖標
5.實現登錄驗證碼
6.實現登錄的前后台編碼
二、具體代碼:
1.添加系統CSS和JS
<script type="text/javascript" src="/Web/Ext/adapter/ext/ext-base-debug.js"></script> <script type="text/javascript" src="/Web/Ext/ext-all-debug.js"></script> <script src="/Web/JavaScript/Common/Global.js" type="text/javascript"></script>
2.構建登錄的Login.aspx的頁面HTML
<body>
<div id="hello-win" class="x-hidden">
<div class="x-window-header">登錄入口</div>
<div id="hello-tabs">
<img src="images/systemBanner.jpg"/>
</div>
<div id='loginInfo' style='color:red;padding-left:120px;'>
請輸入已經通過審核的用戶名與密碼進行登陸!
</div>
</div>
</body>
3.編寫登錄Ext.js的代碼
<script type="text/javascript">
Ext.onReady(function () {
Ext.BLANK_IMAGE_URL = "/ExtOA.Web/Ext/resources/images/default/s.gif";
var loginForm = new Ext.FormPanel({
el: "hello-tabs",
id: "loginForm",
name: "loginForm",
border: false,
//配置項
items: {
//xtype可作為Ext控件的簡寫,都會對應一個Ext控件
xtype: "tabpanel",
//第一項
activeTab: 0,
defaults: { autoHeight: true, bodyStyle: "padding:10px" },
items: [
{
title: "管理員登錄",
//顯示對應的div
contentEl: "loginInfo",
//排列的方式
layout: "form",
defaults: { width: 230 },
//默認的類型
defaultType: "textfield",
//里面具體的內容
items:
[
{
//引入css樣式的寫法
cls: "user",
fieldLabel: "帳號",
name: "staffName",
style: "font-size:15px",
//不允許為空
allowBlank: false,
//提示
blankText: "帳號不允許為空!"
},
{
cls: "key",
fieldLabel: "密碼",
name: "staffPwd",
style: "font-size:15px",
//文本類型
inputType: "password",
allowBlank: false,
blankText: "密碼不允許為空!"
},
{
fieldLabel: "驗證碼",
id: "validateCode",
name: "validateCode",
maxlength: 4,
width: 100,
//大小
style: "font-size:15px",
allowBlank: false,
blankText: "請輸入驗證碼!"
},
]
},
//第二塊選項卡
{
title: "關於本系統",
layout:"",
html: "OA辦公平台 v 1.0<br> 版權所有 孫麗媛 © <br/>技術支持:13593372136@163.com"
}
]
}
});
//創建windows窗體對象
var win = new Ext.Window({
el: "hello-win",
width: 490,
height: 280,
//關閉的時候隱藏
closeAction: "hide",
//內部為透明的
plain: true,
//為模態顯示
modal: true,
//是否允許折疊
collapsible: true,
//是否允許拖動
draggable: true,
//是否允許關閉
closable: false,
//登錄窗體作為項
items: loginForm,
buttons: [
{
text: "確定",
handler: function () {
//判斷是否通過驗證
if (win.getComponent("loginForm").form.isValid()) {
//進行提交
win.getComponent("loginForm").form.submit({
url: "handler/CheckLogin.aspx",
waitTitle: "提示",
waitMsg: "正在登錄驗證,請稍候...",
method: "POST",
success: function (form,action) {
var loginResult = action.result.success;
if (loginResult) {
window.location.href = action.result.href;
} else {
Ext.Msg.alert("提示",action.result.message);
}
},
failure: function (form,action) {
Ext.Msg.alert("提示", action.result.message);
//失敗得到圖片的對象
var imgSN = Ext.getDom("imgSnCode");
if (imgSN)
{
//加參數
imgSN.src="handler/VerifyCode.aspx?datetime=" + (new Date()).getTime();
}
},
});
}
// alert("確定");
}
},
{
text: "重置",
handler: function () {
//獲取loginFrom的主建 或者直接獲取
win.getComponent("loginForm").form.reset();
// loginForm
//alert("重置");
}
}
]
});
//讓窗體顯示
win.show();
//得到驗證碼控件
var db = Ext.getDom("validateCode");
//得到父節點
var db2 = Ext.get(db.parentNode);
//用DomHelper得到getDom 的值
db2.createChild([{ tag: "span", html: " " }, { tag: "img", id: "imgSnCode",style:"cursor:pointer",title:"看不清楚?", src: "handler/VerifyCode.aspx", align: "absbottom" }]);
//讓驗證碼刷新
var imgSN = Ext.get("imgSnCode");
if (imgSN) {
imgSN.on("click", function () {
this.dom.src = "handler/VerifyCode.aspx?datetime=" + (new Date()).getTime();
});
}
})
</script>
5.實現登錄驗證碼
1.后台驗證碼的幫助類:
/// <summary>
/// 產生一個隨機數
/// </summary>
/// <param name="codeCount"></param>
/// <returns></returns>
private string CreateRandomCode(int codeCount)
{
string allChar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,w,x,y,z";
string[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < codeCount; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(35);
if (temp == t)
{
//不相等的話繼續產生
return CreateRandomCode(codeCount);
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
private void CreateImage(string checkCode)
{
//創建寬度
int iwidth = (int)(checkCode.Length * 11.5);
System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);
Graphics g = Graphics.FromImage(image);
Font f = new System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Bold);
Brush b = new System.Drawing.SolidBrush(Color.Blue);
//g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
g.Clear(Color.White);
g.DrawString(checkCode, f, b, 3, 3);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
//清空內容項
Response.ClearContent();
Response.ContentType = "image/Jpeg";
//客戶端輸出二進制數據
Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}
2.前台js的調用:(動態產生圖片)
//得到驗證碼控件
var db = Ext.getDom("validateCode");
//得到父節點
var db2 = Ext.get(db.parentNode);
//用DomHelper得到getDom 的值
db2.createChild([{ tag: "span", html: " " }, { tag: "img", id: "imgSnCode", src: "handler/VerifyCode.aspx", align: "absbottom" }]);
3.后台核心代碼:
1.指向的頁面: (為aspx頁面)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="VerifyCode.aspx.cs" Inherits="VerifyCode" %>
private void Page_Load(object sender, System.EventArgs e) { string checkCode = CreateRandomCode(4);//產生一個數字+字母組合的隨機四位數 Session["CheckCode"] = checkCode; //將此四位數保存至Session,供登錄驗證 CreateImage(checkCode);//根據此驗證碼產生圖片返回到調用端 }
6.實現登錄的前后台編碼
前台:重置按鈕:
win.getComponent("loginForm").form.reset();
確認按鈕:(通過Submit提交)
//判斷是否通過驗證
if (win.getComponent("loginForm").form.isValid()) {
//進行提交
win.getComponent("loginForm").form.submit({
url: "handler/CheckLogin.aspx",
waitTitle: "提示",
waitMsg: "正在登錄驗證,請稍候...",
method: "POST",
success: function (form,action) {
var loginResult = action.result.success;
if (loginResult) {
window.location.href = action.result.href;
} else {
Ext.Msg.alert("提示",action.result.message);
}
},
failure: function (form,action) {
Ext.Msg.alert("提示", action.result.message);
//失敗得到圖片的對象
var imgSN = Ext.getDom("imgSnCode");
if (imgSN)
{
//加參數
imgSN.src="handler/VerifyCode.aspx?datetime=" + (new Date()).getTime();
}
},
});
后台代碼:CheckLogin.aspx
string username = Request["staffName"].ToString();
string password = Request["staffPwd"].ToString();
string reqCheckCode = Request["validateCode"].ToString();
//保存在session中的驗證碼
string checkCode = Session["CheckCode"].ToString();
//思路:先檢查驗證碼是否正確,是否存在用戶名,最后判斷密碼
if (checkCode != reqCheckCode)
{
Response.Write("{success:false,message:'登錄失敗,您輸入的驗證碼和系統產生的不一致,請重新輸入!'}");
}
else {
ExtOA.Biz.UserInfoBiz helper = new ExtOA.Biz.UserInfoBiz();
ExtOA.Ent.UserInfo userinfo = helper.GetUserInfoByUserName(username);
if (userinfo != null)
{
if (userinfo.PassWord == password)
{
Session["CurrentUser"]==userinfo;
Response.Write("{success:true,href:'/Web/Manage/DeskTop/index.aspx',message:''}");
}
else
{
Response.Write("{success:false,message:'登錄失敗,您輸入的密碼不正確,請與管理員聯系!'}");
}
}
else
{
Response.Write("{success:false,message:'登錄失敗,您的用戶名尚未通過驗證,請與管理員聯系!'}");
}
后台代碼部分思路:
1.ExtOA.IDal添加一個新方法
2. ExtOA.SqlServerDal實現ExtOA.IDal方法
3.UserInfoBiz業務邏輯層中調用ExtOA.SqlServerDal中的方法
4.CheckLogin中調用UserInfoBiz
ExtOA.IDal:
UserInfo GetUserInfoByUserName(string usernaem);
ExtOA.SqlServerDal:
/// <summary>
/// 根據用戶名獲取用戶實體
/// </summary>
/// <param name="usernaem"></param>
/// <returns></returns>
public UserInfo GetUserInfoByUserName(string usernaem)
{
UserInfo result = null;
string sql = "Get_UserInfo_By_UserName";
using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(ConnectionString))
{
System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
//command.CommandTimeout = 0;
System.Data.SqlClient.SqlParameter p_userName = command.Parameters.Add("@UserName", SqlDbType.VarChar);
p_userName.Direction = ParameterDirection.Input;
p_userName.IsNullable = false;
p_userName.Value = usernaem;
connection.Open();
using (SqlDataReader dr = command.ExecuteReader())
{
if (dr.Read())
{
result = new UserInfo();
result = PopulateUserInfoFromIDataReader(dr);
}
dr.Close();
}
command.Dispose();
connection.Close();
}
return result;
}
UserInfoBiz:
/// <summary>
/// 根據用戶名獲取用戶的實體
/// </summary>
/// <param name="usernaem"></param>
/// <returns></returns>
public UserInfo GetUserInfoByUserName(string usernaem)
{
try
{
IUserInfoDR dal = UserInfoDal.Create(Config.Instance().Dal, Config.Instance().MyConnectstring);
return dal.GetUserInfoByUserName(usernaem);
}
catch (Exception ex)
{
//log.Error("SetUserInfo err:",ex);
return null;
}
}
效果圖:
