MVC大型商贸系统(库存管理)技术解释(二) 登陆
1.登陆界面
1.1、效果图
1.1 图1
1.2、html 代码:
<!DOCTYPE html>
<html>
<head>
<meta content="text/javascript;charset=utf-8" />
<title>DealWithTransferRepertory</title>
<link href="../../Content/yxsss/js_css/yu.css" rel="stylesheet" />
<link href="../../Content/jquery-easyui-1.3.3/themes/icon.css" rel="stylesheet" />
<link href="../../Content/jquery-easyui-1.3.3/demo/demo.css" rel="stylesheet" />
<link href="../../Content/jquery-easyui-1.3.3/themes/default/easyui.css" rel="stylesheet" />
<link href="../../Content/MyCSS/PublicCSS.css" rel="stylesheet" />
<link href="../../Content/MyCSS/Login.css" rel="stylesheet" />
<script src="../../Content/yxsss/js_css/yu.js"></script>
<script src="../../Content/jquery-easyui-1.3.3/jquery.min.js"></script>
<script src="../../Content/jquery-easyui-1.3.3/jquery.easyui.min.js"></script>
<script src="../../Scripts/MyScript/Login.js"></script>
</head>
<body>
<div class="div2">
<span class="title">大型商贸系统</span>
</div>
<div class="div3" id="Login">
<div class="div4">
<span class="name" id="search_div1">员工号:
<input class="input2" type="text" id="userName" /></span><br />
<span class="name">密 码:
<input class="easyui-validatebox input2" type="password" id="pwd" data-options="validType:'minLength[6]'" /></span><br />
</div>
<div style="height: 55px;">
<span class="name">验证码:<input class="input3" id="idCod2" type="text" /><img id="img1" alt="" src="/WebMain/Page_Load" onclick="getImage();" style="width: 70px; height: 30px;" />
</span>
</div>
<div class="div5">
<button class="button3" onclick="Login1();">登陆</button>
<button class="button4" onclick="window.close();">退出</button>
</div>
<div class="div6">
<button class="button5" onclick="toRetrievePwd()">找回密码</button>
<button class="button6" onclick="logon()">注册</button>
</div>
</div>
<div class="div9" id="Logon">
<div class="div4">
<span id="search_div" class="name"> 员 工 号:
<input class="input2" type="text" id="newUserNumber" />
</span>
<br />
<span class="name">新 密 码:
<input class="easyui-validatebox input2" type="password" id="newPwd1" data-options="validType:'minLength[6]'" /></span><br />
<span class="name">新 密 码:
<input class="easyui-validatebox input2" type="password" id="newPwd2" data-options="validType:'minLength[6]'" /></span><br />
</div>
<div style="height: 50px;">
<span class="name">验 证 码:<input id="idCod1" class="input3" type="text" /><img id="img2" alt="" src="/WebMain/Page_Load" onclick="getImage();"
style="width: 70px; height: 30px;" />
</span>
</div>
<div class="div5">
<button class="button3" onclick="Logon1();">注册</button>
<button class="button4" onclick="returnLogin()">返回</button>
</div>
</div>
<div class="div9" id="retrievePwd">
<p style="font-size: 30px; padding: 20px; color: #7b68ee; text-shadow: 1px 1px 1px #00ffff">请向所属部门超级管理员提交工作证与身份证找回密码!</p>
<div class="div4">
<button class="button4" onclick="returnLogin()">确定</button>
</div>
</div>
<div class="div7">
<div class="div8">©2015 广信软件学院</div>
</div>
</body>
</html>
1.3 、javaScript代码:
$(document).ready(function () {
$('body').fadeIn(2500);//登陆界面渐变呈现
document.onkeydown = function (e) {//注册全局onkeyup事件方法
var ev = document.all ? window.event : e;//获取全局事件
if (ev.keyCode == 13 && temp == 1) {//当事件为Enter按起事件和变量temp值为1时
Login1();//调用登陆方法
} else if (ev.keyCode == 13 && temp == 2) {
Logon1();//调用注册方法
}
}
$("#newUserNumber").keyup(function () {//注册新用户名的按键按起事件
$.getJSON("/WebMain/AutoComplete?tip=" + $("#newUserNumber").val(), function (data) {
$("#newUserNumber").beDropdownlist(data);
});
});
$("#userName").keyup(function () {
$.getJSON("/WebMain/AutoComplete?tip=" + $("#userName").val(), function (data) {//根据已输入的用户名称模糊查询员工表
$("#userName").beDropdownlist(data);//调用动态生成列表方法
});
});
$.extend($.fn.validatebox.defaults.rules, {//重构验证框
minLength: {
validator: function (value, param) {
return value.length >= param[0];
},
message: '密码长度不能小于 {0} 个字符!'
}
});
});
(function ($) {
$.fn.beDropdownlist = function (data) {
var defaults = {
data: ['nothing']
};
var options = { data: data };
options = $.extend(defaults, options); //使得参数覆盖
var bindevent = function (o) {
var tmpid = "tmpselector_" + $(o).attr("id"); //生成临时的id
if ($("#" + tmpid).length > 0) {
$("#" + tmpid).remove();
//return; //退出,不在继续下去
}
var datas = options.data; //数据源
//此处style中设置为absolute
var html = "<div id='" + tmpid + "' style='max-height: 130px;position:absolute;overflow: auto;" +
"width:138px;margin:-10px auto auto 130px;border-buttom:blue;background-color: rgb(181, 213, 242);'><ul class='ui-menu'>";
//动态生成一个div,内含li元素
for (var item in datas) {
html += "<li style='height:20px;line-height:20px; border-bottom: 1px solid blue;font-size:13px;'>" + datas[item]["Employee_number"] + "</li>";
}
html += "</ul></div>";
var left = $(o).offset().left;
var top = $(o).offset().top + $(o).height() + 4;
var finalize = function () {
$("#" + tmpid + " li").unbind('click'); //取消事件绑定
$("#" + tmpid).remove();
};
//设置该div的宽度,位置等。
$("#" + tmpid).width($(o).width() + 100);
$("#" + tmpid).offset({
top: top, left: left
});
$("#" + tmpid).remove();
if (temp == 1) {
$("#search_div1").append(html);
} else {
$("#search_div").append(html);
}
$("#" + tmpid + " li").click(function () {
$(o).val($(this).text());
finalize();
if (fn != undefined) {
fn(); //调用传进来的函数。
}
});
};
this.each(function () { //由于jquery的选择符可能匹配多个对象,所以需要用each,对每个匹配的元素做操作。
if ($(this).is(":text") == true) {
//$(this).keyup(function() {
bindevent($(this)); //设置要做的内容
//});
}
});
};
})(jQuery);
//登录
function Login1() {
var name = $("#userName").val();
var pwd = $("#pwd").val();
var code = $("#idCod2").val();
var paran = /^[a-z0-9_-]{6,18}$/;//限制密码字符只能是字母,数字,_,-的正则表达式
if (name == "" || pwd == "" || code == "") {
ui.error("请先输入完整数据!");
} else if (!paran.test(pwd)) {//验证登陆密码是否规范
ui.alert("密码只能包涵字母、数字、_和-!", 1000, false);
} else {
$.getJSON("/WebMain/Login1?userNumber=" + name + "&pwd=" + pwd
+ "&iCode2=" + code, function (data) {
if (data == "false") {
ui.error("验证码不正确!", 1000, false);
imageCode1();
$("#idCod2").val("");
} else if (data == "true") {
ui.error("用户不存在!", 1000, false);
imageCode1();
} else if (data > 0) {
ui.success("登陆成功!", 2000, false);
$("#Login").fadeOut(2500);
imageCode1();
setTimeout('$("body").fadeOut(2000)', 800);
setTimeout("window.location.href = '/WebMain/Main';", 1800);//调整页面到主界面
} else {
ui.error("密码错误!", 2000, false);
$("#idCod2").val("");
imageCode1();
}
});
}
}
//转到注册界面
var temp = 1;
function logon() {
$("#Login").hide(1500);
$("#Logon").show(1500);
$("#retrievePwd").hide();
imageCode2();
temp = 2;
}
//注册新用户
function Logon1() {
var name = $("#newUserName").val();//获取控件的值赋给变量
var pwd1 = $("#newPwd1").val();
var pwd2 = $("#newPwd2").val();
var code = $("#idCod1").val();
var paran = /^[a-z0-9_-]{6,18}$/;//限制密码字符只能是字母,数字,_,-的正则表达式
if (name == "" || pwd1 == "" || pwd2 == "" || code == "") {//判断是否有控件为空
ui.error("请先输入完整数据", 2000, false);//提示数据不完整
} else if (pwd1.trim() != pwd2.trim()) {//判断密码与确认密码是否一致
$("#newPwd2").val("");
ui.error("两次输入的密码不一致!", 2000, false);
} else if (!paran.test(pwd1)) {//用正则表达式验证密码
ui.alert("密码只能包涵字母、数字、_和-!", 1000, false);
} else {
$.getJSON("/WebMain/Logon1?newUserNumber=" + name + "&newPwd=" + pwd1 + "&idCod=" + code, function (data) {//传参过控制器
if (data == "false") {//返回值为‘false’时执行
ui.error("验证码不正确!", 2000, false);
imageCode2();
$("#idCod1").val("");
return false;
} else if (data == "true") {//返回值为‘true’时执行
ui.error("找不到该工号!", 2000, false);
imageCode2();
return false;
} else if (data == "ok") {//返回值为‘ok’时执行
ui.error("该用户已存在,请直接登录!", 2000, false);
clearLogon();
return false;
} else {
ui.success("注册成功!");
$("#userName").val($("#newUserName").val());
imageCode2();
clearLogon();
temp = 1;
$("#Login").show();
$("#Logon").hide();
}
});
}
}
//清空注册信息
function clearLogon() {
$("#newUserNumber").val("");
$("#newPwd1").val("");
$("#newPwd2").val("");
$("#idCod1").val("");
}
//返回登录界面
function returnLogin() {
$("#Login").show(1500);
$("#Logon").hide(1500);
$("#retrievePwd").hide(1500);
imageCode1();
temp = 1;
}
//转到注册界面
function toRetrievePwd() {
$("#Login").hide(1500);
$("#Logon").hide();
$("#retrievePwd").show(1500);
}
//切换验证码
function getImage() {
if (temp == 1) {
imageCode1();
} else {
imageCode2();
}
}
//登录界面获取验证码
function imageCode1() {
$("#img1").attr("src", "/WebMain/Page_Load?time=" + Date());//获取当前时间以防止验证码不更新
}
//注册界面获取验证码
function imageCode2() {
$("#img2").attr("src", "/WebMain/Page_Load?time=" + Date());
}
1.4、Csharp代码-Controller(控制器):
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using BLL_KuCunGuangLi;
namespace 大型商贸系统.Controllers
{
public class WebMainController : Controller
{
//
// GET: /WebMain/
readonly IWebMains _myWebMain = new WebMain();
[Authorize]
#region 登陆成功跳转到主界面
public ActionResult Main()
{
ViewBag.Id = Session["Employee_name"];
ViewBag.Time = DateTime.Now;
return View();
}
#endregion
#region 跳转到主页面区
public ActionResult Main2()
{
return View();
}
#endregion
#region 跳转到登陆界面
public ActionResult Login()
{
return View();
}
#endregion
#region 左侧菜单
public ActionResult Menu()
{
return View();
}
#endregion
#region 退出登陆
public ActionResult LoginOff()
{
FormsAuthentication.SignOut();//删除身份验证票据
return Redirect("/WebMain/Login");
}
#endregion
#region 生成验证码
/// <summary>
///
/// </summary>
/// <param name="numCount">生成随机数的个数</param>
/// <returns></returns>
private string CreateRandomNum(int numCount)//生成随机字符的方法
{
const string allChar = "1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,y,z";//定义随机字符
string[] charArray = allChar.Split(',');//将随机字符拆分到数组
string randomNum = "";//声明个变量装随机生选择的字符
int temp = -1;//声明一个参数作为标签
var rand = new Random();//实力化个随机数生成器对象
for (int i = 0; i < numCount; i++)//遍历的次数为输入的参数的次数
{
if (temp != -1)//如果标签的值等于数组的其中的下标
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));//计算伪随机数序列起始值的数字
}
int t = rand.Next(60);//生成随机数范围小于60的随机数
if (temp == t)
{
return CreateRandomNum(numCount);//如果生成的随机数与之前的上一个相同,重新执行方法生成。
}
temp = t;
randomNum += charArray[temp];//从数组中获取下标的值为‘temp’的值得元素。
}
return randomNum;//返回已拼接的字符。
}
/// <summary>
///
/// </summary>
/// <param name="validateNum">方法CreateRandomNum()生成的随机字符串</param>
private void CreateImage(string validateNum)//生成图片的方法,参数为上一个方法生成的随机数
{
if (validateNum == null || validateNum.Trim() == string.Empty)//判断参数是否为空
return;
var image = new Bitmap(validateNum.Length * 13 + 20, 30);//实例化一张图片,并设置长宽
Graphics g = Graphics.FromImage(image);//实例化一支画笔
try
{
var random = new Random();
g.Clear(Color.Azure);//格式化画笔,颜色为“Azure”
for (int i = 0; i < 25; i++)//遍历25次,生成成50个随机点
{
int x1 = random.Next(image.Width);//每次生成的随机像素必须在实例化的图像的范围内
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Aquamarine), x1, x2, y1, y2);//用颜色为“Aquamarine”的画笔给每次生成的两个随机点连线
g.DrawLine(new Pen(Color.Bisque), x1 - 2, x2 + 2, y1 - 2, y2 + 2);//用颜色为“Bisque”的画笔给每次生成的两个随机点连线
}
var font = new Font("方正舒体", 15, (FontStyle.Regular | FontStyle.Italic));//设置文本格式
var brush =
new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.BlueViolet,//设置绘制文本的颜色和纹理。
1.2f, true);
g.DrawString(validateNum, font, brush, 5, 5);//根据设置好的字体,颜色,效果,绘制文本的左上角的 x 坐标,绘制文本的左上角的 y 坐标。
for (int i = 0; i < 100; i++)//遍历100次
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next(350)));//获取100个随机点,并设置随机点的颜色为随机颜色
}
g.DrawRectangle(new Pen(Color.Azure), 0, 0, image.Width - 1, image.Height - 1);//绘制矩形框,颜色为“Azure”,
var ms = new MemoryStream();//初始化一个流
image.Save(ms, ImageFormat.Gif);//指定图片格式,并保存到流中
Response.ClearContent();//清空生成的图片
Response.ContentType = "image/Gif";//返回 HTTP MIME 类型
Response.BinaryWrite(ms.ToArray());//将ms流中的内容写入字节数组,并写入http的输出流。
}
finally
{
g.Dispose();//释放画笔
image.Dispose();//释放图片
}
}
public void Page_Load()
{
string validateNum = CreateRandomNum(4);
CreateImage(validateNum);
Session["ValidateNum"] = validateNum.ToLower();//将生成的随机数转换为小写形式保存到共享的session
}
#endregion
#region 注册新用户
/// <summary>
///
/// </summary>
/// <param name="newUserNumber">用户名(员工号)</param>
/// <param name="newPwd">要设置的密码</param>
/// <param name="idCod">验证码</param>
/// <returns></returns>
public ActionResult Logon1(string newUserNumber, string newPwd, string idCod)
{
if (idCod.Trim() != Session["ValidateNum"].ToString())//判断输入的验证码是否与生成的验证码相同
{
return Json("false", JsonRequestBehavior.AllowGet);
}
DataTable dt = _myWebMain.CheckEmployee(newUserNumber);
if (dt.Rows.Count > 0)//检查该员工号是否在员工表存在
{
int newUserNameId = Convert.ToInt32(dt.Rows[0]["Employee_id"]);
DataTable dt1 = _myWebMain.CheckOperator(newUserNameId);//检查员工是否已是用户
if (dt1.Rows.Count > 0)
{
return Json("ok", JsonRequestBehavior.AllowGet);
}
string newPwd1 = ConvertHelperController.ToMd5(newPwd).Substring(9, 20);//调用公共的控制器通过MD5加密,截取第九位开始的20个字符。
int k = _myWebMain.Logon1(newUserNameId, newPwd1);//新增员工id,和密码到用户表完成注册
return Json(k, JsonRequestBehavior.AllowGet);
}
return Json("true", JsonRequestBehavior.AllowGet);//员工号不属于员工表时返回“true”
}
#endregion
#region 登录
/// <summary>
///
/// </summary>
/// <param name="userNumber">员工号</param>
/// <param name="pwd">密码</param>
/// <param name="iCode2">验证码</param>
/// <returns></returns>
public ActionResult Login1(string userNumber, string pwd, string iCode2)
{
if (iCode2.Trim() != Session["ValidateNum"].ToString())//验证验证码
{
return Json("false", JsonRequestBehavior.AllowGet);
}
DataTable dt1 = _myWebMain.CheckOperatorByUserName(userNumber);//检查是否是用户
if (dt1.Rows.Count == 0)
{
return Json("true", JsonRequestBehavior.AllowGet);
}
Session["Employee_name"] = dt1.Rows[0]["Employee_name"].ToString().Trim();//将员工明放入共享容器
string pwd1 = ConvertHelperController.ToMd5(pwd).Substring(9, 20);//转换密码成MD5密码
DataTable dt = _myWebMain.Login1(pwd1);//查询用户id
if (dt.Rows.Count > 0)
{
Session["Operator_id"] = dt.Rows[0]["Operator_id"].ToString();//将用户id放入共享的容器
var ticket = new FormsAuthenticationTicket(
Session["Operator_id"].ToString(),
true,
1000
);// 实例化票证关联用户id
var cookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket));//创建和命名新的 Cookie,并为其赋值。
Response.Cookies.Add(cookie);//新增cookie到Cookies的集合中
return Json(1, JsonRequestBehavior.AllowGet);
}
return Json(0, JsonRequestBehavior.AllowGet);
}
#endregion
#region 模糊查询员工号
public ActionResult AutoComplete(string tip)
{
DataTable dt = _myWebMain.AutoComplete(tip);
List<Dictionary<string, object>> list = ConvertHelperController.DtToList(dt);
return Json(list, JsonRequestBehavior.AllowGet);
}
#endregion
}
}
1.5、Csharp代码-interface(接口)
using System.Data;
namespace BLL_KuCunGuangLi
{
public interface IWebMains
{
DataTable Login1(string pwd1);//登录
DataTable CheckEmployee(string newUserNumber);//根据员工号查询员工ID
DataTable CheckOperator(int newUserNameId);//查询是否已注册
int Logon1(int newUserNameId, string newPwd1);//注册新用户
DataTable AutoComplete(string tip);//模糊查询员工号
DataTable CheckOperatorByUserName(string userNumber);
}
}
1.6、Csharp代码-BLL(逻辑层):
using System.Data;
using System.Data.SqlClient;
using DALPublic;
namespace BLL_KuCunGuangLi
{
public class WebMain : IWebMains
{
readonly DALMethod _myDal = new DALMethod();
#region 登录
public DataTable Login1(string pwd1)
{
SqlParameter[] sql =
{
new SqlParameter("@NB",SqlDbType.Char),
new SqlParameter("@Pwd",SqlDbType.NChar),
};
sql[0].Value = "Login1";
sql[1].Value = pwd1;
return _myDal.DAL_SelectDB_Par("Login", sql);
}
#endregion
public int Logon1(int newUserNameId, string newPwd1)
{
SqlParameter[] sql =
{
new SqlParameter("@NB",SqlDbType.Char),
new SqlParameter("@Employee_id",SqlDbType.Int),
new SqlParameter("@Pwd",SqlDbType.Char),
};
sql[0].Value = "Logon1";
sql[1].Value = newUserNameId;
sql[2].Value = newPwd1;
return _myDal.DAL_OPTableDB_Par("Login", sql);
}
public DataTable CheckEmployee(string newUserNumber)
{
SqlParameter[] sql =
{
new SqlParameter("@NB",SqlDbType.Char),
new SqlParameter("@Employee_number",SqlDbType.Char),
};
sql[0].Value = "CheckEmployee";
sql[1].Value = newUserNumber;
return _myDal.DAL_SelectDB_Par("Login", sql);
}
#region 模糊查询员工号
public DataTable AutoComplete(string tip)
{
SqlParameter[] sql =
{
new SqlParameter("@NB", SqlDbType.Char),
new SqlParameter("@tip", SqlDbType.Char),
};
sql[0].Value = "AutoComplete";
sql[1].Value = tip;
return _myDal.DAL_SelectDB_Par("Login", sql);
}
public DataTable CheckOperatorByUserName(string userNumber)
{
SqlParameter[] sql =
{
new SqlParameter("@NB", SqlDbType.NChar),
new SqlParameter("@Employee_number", SqlDbType.NChar),
};
sql[0].Value = "CheckOperatorByUserName";
sql[1].Value = userNumber;
return _myDal.DAL_SelectDB_Par("Login", sql);
}
#endregion
#region 查询是否已注册
public DataTable CheckOperator(int newUserNameId)
{
SqlParameter[] sql =
{
new SqlParameter("@NB", SqlDbType.NChar),
new SqlParameter("@Employee_id", SqlDbType.Int),
};
sql[0].Value = "CheckOperator";
sql[1].Value = newUserNameId;
return _myDal.DAL_SelectDB_Par("Login", sql);
}
#endregion
}
}
1.7 SQl-存储过程
ALTER PROCEDURE [dbo].[Login]
@NB char(100)='',@Employee_number nchar(20)='',@Pwd char(20)='',@Employee_id int=0,
@tip char(12)=''
AS
BEGIN
if(@NB='CheckOperatorByUserName')
begin
SELECT Operator.Operator_id, Eemployee.Employee_name
FROM Operator INNER JOIN
Eemployee ON Operator.Employee_id = Eemployee.Employee_id
WHERE (Operator.Employee_id =
(SELECT Employee_id
FROM Eemployee AS Eemployee_1
WHERE (Employee_number = RTRIM(@Employee_number))))
end
if(@NB='Login1') --登陆
begin
SELECT Operator_id
FROM Operator
where Pwd=RTRIM(@Pwd)
end
if(@NB='CheckOperator') --查询用户
begin
SELECT Operator_id
FROM Operator
where Employee_id=@Employee_id
end
if(@NB='AutoComplete') --模糊查询员工
begin
SELECT Employee_number
FROM Eemployee
where Employee_number like '%'+RTRIM(@tip)+'%'
end
if(@NB='Logon1') --注册用户
begin
INSERT INTO Operator
(Employee_id, Pwd)
VALUES (@Employee_id,@Pwd)
end
if(@NB='CheckEmployee') --查询员工
begin
SELECT Employee_id
FROM Eemployee
where Employee_number=ltrim(rtrim(@Employee_number))
end
END
2、控件实现详解:
2.1、textbox文本框:
2.1.1、效果:
2.1.2、HTML代码:
<span class="name" id="search_div1">员工号:
<input class="input2" type="text" id="userName" /></span><br />
2.1.3、JavaScript代码:获取值
var name = $("#userName").val();
2.2、textbox密码输入框:
2.2.1、Html代码:
<span class="name">密 码:
<input class="easyui-validatebox input2" type="password" id="pwd" data-options="validType:'minLength[6]'" /></span><br />
2.2.2JavaScript代码:获取值
$.extend($.fn.validatebox.defaults.rules, {//重构验证框
minLength: {
validator: function (value, param) {
return value.length >= param[0];
},
message: '密码长度不能小于 {0} 个字符!'
}
});
var pwd = $("#pwd").val();
2.3、验证码:
2.3.1、Html代码:
<span class="name">验证码:<input class="input3" id="idCod2" type="text" /><img id="img1" alt="" src="/WebMain/Page_Load" onclick="getImage();" style="width: 70px; height: 30px;" />
</span>
2.3.2、javaScript 代码:
//登录界面获取验证码
function imageCode1() {
$("#img1").attr("src", "/WebMain/Page_Load?time=" + Date());//获取当前时间以防止验证码不更新
}
2.3.3、Csharp-Controller代码:
#region 生成验证码
/// <summary>
///
/// </summary>
/// <param name="numCount">生成随机数的个数</param>
/// <returns></returns>
private string CreateRandomNum(int numCount)//生成随机字符的方法
{
const string allChar = "1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,y,z";//定义随机字符
string[] charArray = allChar.Split(',');//将随机字符拆分到数组
string randomNum = "";//声明个变量装随机生选择的字符
int temp = -1;//声明一个参数作为标签
var rand = new Random();//实力化个随机数生成器对象
for (int i = 0; i < numCount; i++)//遍历的次数为输入的参数的次数
{
if (temp != -1)//如果标签的值等于数组的其中的下标
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));//计算伪随机数序列起始值的数字
}
int t = rand.Next(60);//生成随机数范围小于60的随机数
if (temp == t)
{
return CreateRandomNum(numCount);//如果生成的随机数与之前的上一个相同,重新执行方法生成。
}
temp = t;
randomNum += charArray[temp];//从数组中获取下标的值为‘temp’的值得元素。
}
return randomNum;//返回已拼接的字符。
}
/// <summary>
///
/// </summary>
/// <param name="validateNum">方法CreateRandomNum()生成的随机字符串</param>
private void CreateImage(string validateNum)//生成图片的方法,参数为上一个方法生成的随机数
{
if (validateNum == null || validateNum.Trim() == string.Empty)//判断参数是否为空
return;
var image = new Bitmap(validateNum.Length * 13 + 20, 30);//实例化一张图片,并设置长宽
Graphics g = Graphics.FromImage(image);//实例化一支画笔
try
{
var random = new Random();
g.Clear(Color.Azure);//格式化画笔,颜色为“Azure”
for (int i = 0; i < 25; i++)//遍历25次,生成成50个随机点
{
int x1 = random.Next(image.Width);//每次生成的随机像素必须在实例化的图像的范围内
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Aquamarine), x1, x2, y1, y2);//用颜色为“Aquamarine”的画笔给每次生成的两个随机点连线
g.DrawLine(new Pen(Color.Bisque), x1 - 2, x2 + 2, y1 - 2, y2 + 2);//用颜色为“Bisque”的画笔给每次生成的两个随机点连线
}
var font = new Font("方正舒体", 15, (FontStyle.Regular | FontStyle.Italic));//设置文本格式
var brush =
new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.BlueViolet,//设置绘制文本的颜色和纹理。
1.2f, true);
g.DrawString(validateNum, font, brush, 5, 5);//根据设置好的字体,颜色,效果,绘制文本的左上角的 x 坐标,绘制文本的左上角的 y 坐标。
for (int i = 0; i < 100; i++)//遍历100次
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next(350)));//获取100个随机点,并设置随机点的颜色为随机颜色
}
g.DrawRectangle(new Pen(Color.Azure), 0, 0, image.Width - 1, image.Height - 1);//绘制矩形框,颜色为“Azure”,
var ms = new MemoryStream();//初始化一个流
image.Save(ms, ImageFormat.Gif);//指定图片格式,并保存到流中
Response.ClearContent();//清空生成的图片
Response.ContentType = "image/Gif";//返回 HTTP MIME 类型
Response.BinaryWrite(ms.ToArray());//将ms流中的内容写入字节数组,并写入http的输出流。
}
finally
{
g.Dispose();//释放画笔
image.Dispose();//释放图片
}
}
public void Page_Load()
{
string validateNum = CreateRandomNum(4);
CreateImage(validateNum);
Session["ValidateNum"] = validateNum.ToLower();//将生成的随机数转换为小写形式保存到共享的session
}
3、数据库表结构
3.1、数据库表:
用到的主要的表有:员工表,部门表,用户表,员工职务表
表1
表2
表3
表4
表5
3.2、主要表结构