C#用AJAX验证用户登陆 使用三层结构
DAL:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
namespace DAL
{
public static class DBHelper
{
/// <summary>
/// 创建DbCommand的方法
/// </summary>
/// <returns></returns>
public static DbCommand CreateCommand()
{
string connectionString = ConfigurationManager.AppSettings["connString"];
string providerName = ConfigurationManager.AppSettings["provName"];
DbProviderFactory factory = DbProviderFactories.GetFactory(providerName);
DbConnection conn = factory.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = conn.CreateCommand();
return cmd;
}
/// <summary>
/// 返回DataTabale的方法,第一重重载
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static DataTable ExecuteCommand(string sql)
{
DataTable table = new DataTable();
DbDataReader reader = null;
DbCommand cmd = DBHelper.CreateCommand();
cmd.CommandText = sql;
try
{
cmd.Connection.Open();
reader = cmd.ExecuteReader();
table.Load(reader);
}
catch (Exception ex)
{
throw ex;
}
finally
{
reader.Close();
cmd.Connection.Close();
}
return table;
}
/// <summary>
/// 返回DataTabale的方法,第二重重载,可执行存储过程
/// </summary>
/// <param name="sql"></param>
/// <param name="values"></param>
/// <returns></returns>
public static DataTable ExecuteCommand(string sql, params DbParameter[] values)
{
DataTable table = new DataTable();
DbDataReader reader = null;
DbCommand cmd = DBHelper.CreateCommand();
cmd.CommandText = sql;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(values);
try
{
cmd.Connection.Open();
reader = cmd.ExecuteReader();
table.Load(reader);
}
catch (Exception ex)
{
throw ex;
}
finally
{
reader.Close();
cmd.Connection.Close();
}
return table;
}
/// <summary>
/// 执行修改、删除、添加数据库中表的方法,第一重重载
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static int ExecuteNoQuery(string sql)
{
int affect = -1;
DbCommand cmd = DBHelper.CreateCommand();
cmd.CommandText = sql;
try
{
cmd.Connection.Open();
affect = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Connection.Close();
}
return affect;
}
/// <summary>
/// 执行修改、删除、添加数据库中表的方法,第二重重载,可执行存储过程
/// </summary>
/// <param name="sql"></param>
/// <param name="values"></param>
/// <returns></returns>
public static int ExecuteNoQuery(string sql,params DbParameter[] values)
{
int affect = -1;
DbCommand cmd = DBHelper.CreateCommand();
cmd.CommandText = sql;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(values);
try
{
cmd.Connection.Open();
affect = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Connection.Close();
}
return affect;
}
/// <summary>
/// 返回数据表的第一行第一列,第一重重载
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static string GetScalar(string sql)
{
string result = null;
DbCommand cmd = DBHelper.CreateCommand();
cmd.CommandText = sql;
try
{
cmd.Connection.Open();
result = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
result = (string)(cmd.ExecuteScalar());
}
finally
{
cmd.Connection.Close();
}
return result;
}
/// <summary>
/// 返回数据表的第一行第一列,第二重重载,可执行存储过程
/// </summary>
/// <param name="sql"></param>
/// <param name="values"></param>
/// <returns></returns>
public static string GetScalar(string sql, params DbParameter[] values)
{
string result = null;
DbCommand cmd = null;
cmd.CommandText = sql;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(values);
try
{
cmd = DBHelper.CreateCommand();
cmd.Connection.Open();
result = cmd.ExecuteScalar().ToString();
}
catch (Exception ex)
{
result = (string)(cmd.ExecuteScalar());
}
finally
{
cmd.Connection.Close();
}
return result;
}
/// <summary>
/// 把数据转换成XML形式输出,第一重重载
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static string GetXmlReaderString(string sql)
{
StringBuilder xmlString = new StringBuilder();
SqlCommand sqlcmd = (SqlCommand)(DBHelper.CreateCommand());
sqlcmd.CommandText = sql;
try
{
sqlcmd.Connection.Open();
XmlReader reader = sqlcmd.ExecuteXmlReader();
reader.Read();
xmlString.Append("<root>");
while (!reader.EOF)
{
xmlString.Append(reader.ReadOuterXml());
}
xmlString.Append("</root>");
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlcmd.Connection.Close();
}
return xmlString.ToString();
}
/// <summary>
/// 把数据转换成XML形式输出,第二重重载,可执行存储过程
/// </summary>
/// <param name="sql"></param>
/// <param name="values"></param>
/// <returns></returns>
public static string GetXmlReaderString(string sql,params SqlParameter[] values)
{
StringBuilder xmlString = new StringBuilder();
SqlCommand sqlcmd = (SqlCommand)(DBHelper.CreateCommand());
sqlcmd.CommandText = sql;
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddRange(values);
try
{
sqlcmd.Connection.Open();
XmlReader reader = sqlcmd.ExecuteXmlReader();
reader.Read();
xmlString.Append("<root>");
while (!reader.EOF)
{
xmlString.Append(reader.ReadOuterXml());
}
xmlString.Append("</root>");
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlcmd.Connection.Close();
}
return xmlString.ToString();
}
}
}
Model:
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
namespace DAL
{
public static class DBHelper
{
/// <summary>
/// 创建DbCommand的方法
/// </summary>
/// <returns></returns>
public static DbCommand CreateCommand()
{
string connectionString = ConfigurationManager.AppSettings["connString"];
string providerName = ConfigurationManager.AppSettings["provName"];
DbProviderFactory factory = DbProviderFactories.GetFactory(providerName);
DbConnection conn = factory.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand cmd = conn.CreateCommand();
return cmd;
}
/// <summary>
/// 返回DataTabale的方法,第一重重载
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static DataTable ExecuteCommand(string sql)
{
DataTable table = new DataTable();
DbDataReader reader = null;
DbCommand cmd = DBHelper.CreateCommand();
cmd.CommandText = sql;
try
{
cmd.Connection.Open();
reader = cmd.ExecuteReader();
table.Load(reader);
}
catch (Exception ex)
{
throw ex;
}
finally
{
reader.Close();
cmd.Connection.Close();
}
return table;
}
/// <summary>
/// 返回DataTabale的方法,第二重重载,可执行存储过程
/// </summary>
/// <param name="sql"></param>
/// <param name="values"></param>
/// <returns></returns>
public static DataTable ExecuteCommand(string sql, params DbParameter[] values)
{
DataTable table = new DataTable();
DbDataReader reader = null;
DbCommand cmd = DBHelper.CreateCommand();
cmd.CommandText = sql;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(values);
try
{
cmd.Connection.Open();
reader = cmd.ExecuteReader();
table.Load(reader);
}
catch (Exception ex)
{
throw ex;
}
finally
{
reader.Close();
cmd.Connection.Close();
}
return table;
}
/// <summary>
/// 执行修改、删除、添加数据库中表的方法,第一重重载
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static int ExecuteNoQuery(string sql)
{
int affect = -1;
DbCommand cmd = DBHelper.CreateCommand();
cmd.CommandText = sql;
try
{
cmd.Connection.Open();
affect = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Connection.Close();
}
return affect;
}
/// <summary>
/// 执行修改、删除、添加数据库中表的方法,第二重重载,可执行存储过程
/// </summary>
/// <param name="sql"></param>
/// <param name="values"></param>
/// <returns></returns>
public static int ExecuteNoQuery(string sql,params DbParameter[] values)
{
int affect = -1;
DbCommand cmd = DBHelper.CreateCommand();
cmd.CommandText = sql;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(values);
try
{
cmd.Connection.Open();
affect = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Connection.Close();
}
return affect;
}
/// <summary>
/// 返回数据表的第一行第一列,第一重重载
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static string GetScalar(string sql)
{
string result = null;
DbCommand cmd = DBHelper.CreateCommand();
cmd.CommandText = sql;
try
{
cmd.Connection.Open();
result = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
result = (string)(cmd.ExecuteScalar());
}
finally
{
cmd.Connection.Close();
}
return result;
}
/// <summary>
/// 返回数据表的第一行第一列,第二重重载,可执行存储过程
/// </summary>
/// <param name="sql"></param>
/// <param name="values"></param>
/// <returns></returns>
public static string GetScalar(string sql, params DbParameter[] values)
{
string result = null;
DbCommand cmd = null;
cmd.CommandText = sql;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(values);
try
{
cmd = DBHelper.CreateCommand();
cmd.Connection.Open();
result = cmd.ExecuteScalar().ToString();
}
catch (Exception ex)
{
result = (string)(cmd.ExecuteScalar());
}
finally
{
cmd.Connection.Close();
}
return result;
}
/// <summary>
/// 把数据转换成XML形式输出,第一重重载
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static string GetXmlReaderString(string sql)
{
StringBuilder xmlString = new StringBuilder();
SqlCommand sqlcmd = (SqlCommand)(DBHelper.CreateCommand());
sqlcmd.CommandText = sql;
try
{
sqlcmd.Connection.Open();
XmlReader reader = sqlcmd.ExecuteXmlReader();
reader.Read();
xmlString.Append("<root>");
while (!reader.EOF)
{
xmlString.Append(reader.ReadOuterXml());
}
xmlString.Append("</root>");
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlcmd.Connection.Close();
}
return xmlString.ToString();
}
/// <summary>
/// 把数据转换成XML形式输出,第二重重载,可执行存储过程
/// </summary>
/// <param name="sql"></param>
/// <param name="values"></param>
/// <returns></returns>
public static string GetXmlReaderString(string sql,params SqlParameter[] values)
{
StringBuilder xmlString = new StringBuilder();
SqlCommand sqlcmd = (SqlCommand)(DBHelper.CreateCommand());
sqlcmd.CommandText = sql;
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddRange(values);
try
{
sqlcmd.Connection.Open();
XmlReader reader = sqlcmd.ExecuteXmlReader();
reader.Read();
xmlString.Append("<root>");
while (!reader.EOF)
{
xmlString.Append(reader.ReadOuterXml());
}
xmlString.Append("</root>");
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlcmd.Connection.Close();
}
return xmlString.ToString();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Model
{
public class User
{
string username;
string password;
public string Username
{
get { return this.username; }
set { this.username = value; }
}
public string Password
{
get { return this.password; }
set { this.password = value; }
}
}
}
BLL:
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Model
{
public class User
{
string username;
string password;
public string Username
{
get { return this.username; }
set { this.username = value; }
}
public string Password
{
get { return this.password; }
set { this.password = value; }
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model;
using DAL;
using System.Data;
namespace BLL
{
public class BLLCheckUser
{
public static string Check(User user)
{
string sql = "select * from tb_User where UserId='" + user.Username + "' and Password='" + user.Password + "'";
DataTable table = DBHelper.ExecuteCommand(sql);
if (table.Rows.Count > 0)
{
if(table.Rows[0]["UserId"].ToString()!="")
return "true";
}
return "false";
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model;
using DAL;
using System.Data;
namespace BLL
{
public class BLLCheckUser
{
public static string Check(User user)
{
string sql = "select * from tb_User where UserId='" + user.Username + "' and Password='" + user.Password + "'";
DataTable table = DBHelper.ExecuteCommand(sql);
if (table.Rows.Count > 0)
{
if(table.Rows[0]["UserId"].ToString()!="")
return "true";
}
return "false";
}
}
}
页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>
<!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 runat="server">
<title></title>
<style type="text/css">
body{
text-align: center;
font-size: 12px;
color:#666;
font-family: font-family: Arial, Helvetica, sans-serif;
}
table
{
margin-top: 160px;
padding-top: 30px;
padding-bottom: 30px;
border: solid 2px #333;
background: #fafcfd;
}
h1
{
width: 200px;
font-size:24px;
text-align: center;
margin: 0;
padding: 0;
margin-left: 100px;
}
td{
width: 200px;
height: 30px;
padding: 6px;
}
.field
{
width: 120px;
border: solid 1px #ccc;
}
.login_btn
{
border: solid 1px #ccc;
background: #fafcfd;
text-align:center;
width: 60px;
font-size: 12px;
color: #666;
margin: 10px;
padding-top:2px;
line-height: 16px;
}
</style>
</head>
<body>
<form action="Office.aspx" method="post">
<table align="center">
<tr>
<td colspan="2"><h1>Office办公自动化</h1></td>
</tr>
<tr>
<td align="right">用户名:</td>
<td align="left"><input type="text" size="9" class="field" id="_name"/></td>
</tr>
<tr>
<td align="right">密 码:</td>
<td align="left"><input type="password" class="field" id="_pwd"/></td>
</tr>
<tr>
<td align="right"><input type="button" value="登陆" class="login_btn" onclick="sendTo()"/><input type="submit" id="submit" style="display:none"/></td>
<td align="left"><input type="reset"value="取消" class="login_btn"/></td>
</tr>
</table>
</form>
</body>
</html>
<!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 runat="server">
<title></title>
<style type="text/css">
body{
text-align: center;
font-size: 12px;
color:#666;
font-family: font-family: Arial, Helvetica, sans-serif;
}
table
{
margin-top: 160px;
padding-top: 30px;
padding-bottom: 30px;
border: solid 2px #333;
background: #fafcfd;
}
h1
{
width: 200px;
font-size:24px;
text-align: center;
margin: 0;
padding: 0;
margin-left: 100px;
}
td{
width: 200px;
height: 30px;
padding: 6px;
}
.field
{
width: 120px;
border: solid 1px #ccc;
}
.login_btn
{
border: solid 1px #ccc;
background: #fafcfd;
text-align:center;
width: 60px;
font-size: 12px;
color: #666;
margin: 10px;
padding-top:2px;
line-height: 16px;
}
</style>
</head>
<body>
<form action="Office.aspx" method="post">
<table align="center">
<tr>
<td colspan="2"><h1>Office办公自动化</h1></td>
</tr>
<tr>
<td align="right">用户名:</td>
<td align="left"><input type="text" size="9" class="field" id="_name"/></td>
</tr>
<tr>
<td align="right">密 码:</td>
<td align="left"><input type="password" class="field" id="_pwd"/></td>
</tr>
<tr>
<td align="right"><input type="button" value="登陆" class="login_btn" onclick="sendTo()"/><input type="submit" id="submit" style="display:none"/></td>
<td align="left"><input type="reset"value="取消" class="login_btn"/></td>
</tr>
</table>
</form>
</body>
</html>
JS脚本:
function InitHttpRequest()
{
var HttpRequest=null;
if(window.ActiveXObject)
{
try{
HttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try{
HttpRequest=new ActiveXObject("Microsofr.XMLHTTP");
}
catch(e)
{
}
}
}
else if(window.XMLHttpRequest)
{
HttpRequest = new XMLHttpRequest();
}
return HttpRequest;
}
function sendRequest(url,data)
{
var Request = InitHttpRequest();
Request.onreadystatechange = function() {
if (Request.readyState == 4 && Request.Status == 200) {
var recieve = Request.responseText;
if (recieve == "true") {
document.getElementById("submit").click();
//alert("验证通过!");
}
else {
alert("用户名或密码错误!");
}
}
}
Request.open("POST", url, false);
Request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
Request.send(data);
}
function sendTo()
{
var url = "Ajax/CheckUser.aspx";
var post_str = "_name=" + document.getElementById("_name").value + "&_pwd=" + document.getElementById("_pwd").value;//构造POST参数
sendRequest(url,post_str);
}
{
var HttpRequest=null;
if(window.ActiveXObject)
{
try{
HttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try{
HttpRequest=new ActiveXObject("Microsofr.XMLHTTP");
}
catch(e)
{
}
}
}
else if(window.XMLHttpRequest)
{
HttpRequest = new XMLHttpRequest();
}
return HttpRequest;
}
function sendRequest(url,data)
{
var Request = InitHttpRequest();
Request.onreadystatechange = function() {
if (Request.readyState == 4 && Request.Status == 200) {
var recieve = Request.responseText;
if (recieve == "true") {
document.getElementById("submit").click();
//alert("验证通过!");
}
else {
alert("用户名或密码错误!");
}
}
}
Request.open("POST", url, false);
Request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
Request.send(data);
}
function sendTo()
{
var url = "Ajax/CheckUser.aspx";
var post_str = "_name=" + document.getElementById("_name").value + "&_pwd=" + document.getElementById("_pwd").value;//构造POST参数
sendRequest(url,post_str);
}
异步调用页面:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using BLL;
public partial class AJAX_CheckUser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string username = Request.Params["_name"];
string password = Request.Params["_pwd"];
User user = new User();
user.Username = username;
user.Password = password;
string check = BLLCheckUser.Check(user);
Response.Write(check);
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using BLL;
public partial class AJAX_CheckUser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string username = Request.Params["_name"];
string password = Request.Params["_pwd"];
User user = new User();
user.Username = username;
user.Password = password;
string check = BLLCheckUser.Check(user);
Response.Write(check);
}
}