【个人机房重构】——三层架构,系统登录

在进行个人版机房重构的之前,系统登录的例子是每个人必敲的 。在这里,就不过多的阐述关于三层的理解了 。
首先:

【个人机房重构】——三层架构,系统登录

文章插图
这是三层设计:
【个人机房重构】——三层架构,系统登录

文章插图
下边是具体的代码:
【个人机房重构】——三层架构,系统登录

文章插图
【U层】
Public Class frmLogin'登录Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click'判断用户名、密码是否为空If Trim(txtUname.Text) = "" Or Trim(txtPwd.Text) = "" ThenMsgBox("登录信息不能为空")End IfDim enUser As New Entity.UserInfoEntity'实例化新的UserInfoEntity,用来传递B层的实体Dim BCheck As New BLL.LoginBLL'定义BCheck,用来传递参数'将输入的用户名、密码传递给实体层enUser.userName = Trim(txtUname.Text)enUser.Pwd = txtPwd.TextIf BCheck.Check(enUser) = True ThenMsgBox("登录成功!")ElseMsgBox("登录失败!")End IfEnd Sub'取消Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.ClickMe.Close()End SubEnd Class
【B层】
Public Class LoginBLLFunction Check(ByVal user As Entity.UserInfoEntity) As BooleanDim DUser As New DAL.LoginDAL'实例化新对象Dim BUser As New Entity.UserInfoEntity'传值BUser.userName = user.userNameBUser.Pwd = user.PwdBUser = DUser.Check(BUser)If BUser.Pwd = user.Pwd ThenReturn TrueElseReturn FalseEnd IfEnd FunctionEnd Class
【D层】
Imports System.Data.SqlClientImports System.DataPublic Class LoginDAL'创建数据库连接'Dim ConnStr As String = "Data Source=localhost;Initial Catalog=ChargeSystem;User ID=sa;Pwd=123"Dim ConnStr As String = "Data Source=192.168.24.207;Initial Catalog=ChargeSystem;User ID=sa;Pwd=123"Dim conn As SqlConnection = New SqlConnection(ConnStr)Function Check(ByVal user As Entity.UserInfoEntity) As Entity.UserInfoEntity'传递实体'其实下面的这段程序就相当于dim sql as string ="selectID,UserName,PWD From Users Where UserName='"User.UserName"' And PWD='"User.PWD"'"'而写成这个程序块是为了防止Sql注入,即安全性考虑 。'@UserName相当于传了一个参数,("@UserName", User.UserName)相当于给参数名字传递了参数 。Dim sql As String = "select * from T_UserInfo where userName=@userName and Pwd=@Pwd;"Dim cmd As SqlCommand = New SqlCommand(sql, conn)cmd.Parameters.Add(New SqlParameter("@userName", user.userName))cmd.Parameters.Add(New SqlParameter("@Pwd", user.Pwd))Dim users As New Entity.UserInfoEntityDim read As SqlDataReaderTryconn.Open()'打开数据库read = cmd.ExecuteReader'执行查询语句,并生成一个DataReadread.Read()users.userName = read.Item("userName")users.Pwd = read.Item("Pwd")Return userCatch ex As Exceptionuser.Pwd = ""Return userEnd TryEnd FunctionEnd Class
【】
Public Class UserInfoEntity'用户表实体'定义用户表中的userName、name、Pwd、level、registerDate、registerTeacherPrivate _userName As String'定义私有属性_UserName为string类型Public Property userName() As String'定义共有属性userName为string类型Get'只读Return _userNameEnd GetSet(ByVal value As String)'只写_userName = value'为strserName赋值End SetEnd PropertyPrivate _Pwd As StringPublic Property Pwd() As StringGetReturn _PwdEnd GetSet(ByVal value As String)_Pwd = valueEnd SetEnd Property
B层主管业务逻辑,也就是说和业务有关的放在B层 。U层是表现层,主管和用户的互动,用户输入,以及向用户展示都是U层的事 。D层为数据访问层,主管和数据库打交道 。