这次就是我的七层登录的实践了,我登录写了两条线,第一条线就是判断用户是否存在,第二条线就是判断密码是不是正确,登录权限的问题。
我先把所有的代码粘贴出来,后面会给说注意事项,保证大家一次登录成功。后面的解释很重要,代码只是展示。

Entity层(Model层)

一个类,当我们需要一个对象的时候,就实例化(new)这个类就ok了,这个Entity层我们在各个层都引用到了,
登录两个属性就够用了。
Public Class AdminEntity                 
    Private _AdminID As String        '定义用户ID      
    Public Property AdminID() As String
            Get
                Return _AdminID
            End Get
            Set(value As String)
                _AdminID = value
            End Set
    End Property

    Private _PassWord As String       '定义密码 
    Public Property Password() As String
            Get
                Return _PassWord
            End Get
            Set(value As String)
                _PassWord = value
            End Set
    End Property
End Class

UI层

Public Class FrmLogin
        Public AdminID As String                                  '定义一个公共变量存储登录名
        Private Sub BtnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click        
            AdminID = txtAdminID.Text.Trim                      '存储账号未来用到登录有没有不很重要
            '第一条线开始
            Dim AdminInfo As New AdminEntity()                    '实例化一个对象,通过Entity实例一个对象

            AdminInfo.AdminID = txtAdminID.Text.Trim                '给对象赋值
            AdminInfo.Password = txtPassWord.Text.Trim
            '定义一个外观层对象  
            Dim facadeLogin As New LoginFacade                     '实例化Facade层
            Dim strResult As Boolean                               '定义一返回值接受对象
            '将U层文本框的内容传入外观曾,然后通过外观层传入B层
            strResult = facadeLogin.CheckAdmin(AdminInfo)          '调用Facade层方法
            If strResult = False Then                              '显示自己的结果
                MsgBox("用户不存在,请重新输入!", , "温馨提示")
                txtAdminID.Text = ""
                txtPassWord.Text = ""
                txtAdminID.Focus()                                 '光标出现的位置
            Else
            '第二条线开始和第一条线是一样的。
                Dim table As DataTable      
                table = facadeLogin.CheckPassWord(AdminInfo)
                If txtPassWord.Text.Trim = Trim(table.Rows(0).Item(1)) Then
                    'MsgBox("登录成功!", , "温馨提示")
                    txtAdminID.Text = ""
                    txtPassWord.Text = ""
                    Select Case Trim(table.Rows(0).Item(2))                  '利用传回的数据判断权限
                        Case "管理员"     ' Or "操作员"
                            FrmAdminMian.Show()
                            'FrmAdminMian.MenuAdmin.Visible = False
                        Case "操作员"
                            FrmAdminMian.Show()
                            FrmAdminMian.MenuAdmin.Visible = False
                        Case "用户"
                            FrmUserMian.Show()
                    End Select
                    Me.Hide()
                Else
                    MsgBox("登录失败!", , "温馨提示")
                End If
            End If
        End Sub
    End Class

Facade层(外观层)

Public Class LoginFacade
     '检查用户是否存在  
      Public Function CheckAdmin(ByVal AdminInfo As Entity.AdminEntity) As Boolean
          Dim isUserExists As New BLL.LoginBLL()     '实例化B层 生成对象。
          Dim flag As Boolean                        '定义返回空间
          flag = isUserExists.ExistAdmin(AdminInfo)
          If flag = True Then                        '接受BLL层中返回值
              Return True
          Else
              Return False
          End If
      End Function
     '检查密码是否正确  
      Public Function CheckPassWord(ByVal AdminInfo As Entity.AdminEntity) As DataTable
          Dim isPassWordRight As New BLL.LoginBLL()
          Dim table As DataTable
          table = isPassWordRight.RightPassWord(AdminInfo)
          Return table
     End Function
End Class

BLL层

Public Class LoginBLL
    '检查用户是否存在
    Public Function ExistAdmin(ByVal AdminInfo As Entity.AdminEntity) As Boolean
        '定义并实例化一个工厂  
        Dim Factory As New Factory.LoginFactory() 

        Dim IAdmin As IDAL.ILoginIDAL               '定义一个接口变量
        Dim table As DataTable
        IAdmin = Factory.CreateIUser                '调用检查用户的工厂方法  

        Dim flag As Boolean                         '定义布尔型变量
        table = IAdmin.SelectAdmin(AdminInfo)       '调用检查用户的工厂方法   
        If table.Rows.Count = 0 Then
            flag = False
        Else
            flag = True
        End If
        Return flag
    End Function
    '检查密码是否正确  
    Public Function RightPassWord(ByVal AdminInfo As Entity.AdminEntity) As DataTable
        Dim Factory As New Factory.LoginFactory()       '定义工厂并实例化工厂变量factory
        Dim IAdmin As IDAL.ILoginIDAL                   '定义接口变量IUser 
        Dim table As DataTable                          '中间变量,用于存储D层查询到的数据 

        IAdmin = Factory.CreateIUser                    '调用工厂的CreateUser方法创建iuser接口实例 
        table = IAdmin.SelectAdmin(AdminInfo)           '调用接口的方法UserIsExist,并将返回值返回给flag

        Return table
    End Function

End Class

Factory层

Public Class LoginFactory
    Dim strDB As String = System.Configuration.ConfigurationManager.AppSettings("DB") '配置文件中的名称  
    Public Function CreateIUser() As IDAL.ILoginIDAL
         Dim classname As String = strDB + "." + "LoginDAL"
        '反射的关键代码(返回接口)
        Dim IAdmin As IDAL.ILoginIDAL
        'CType函数将返回表达式显示的转换为指定的数据类型、对象、结构、类或接口后的结果 
        IAdmin = CType(Assembly.Load(strDB).CreateInstance(classname), IDAL.ILoginIDAL) '返回LoginIUserInfo  
        Return IAdmin
    End Function
End Class

IDAL层

Public Interface ILoginIDAL
    '定义查找用户的方法,用于在数据库中查找用户  
    Function SelectAdmin(ByVal AdminInfo As Entity.AdminEntity) As DataTable
End Interface

DAL层

Public Class LoginDAL : Implements IDAL.ILoginIDAL
    '实现接口中定义的方法  
    Public Function selectUser(AdminInfo As AdminEntity) As DataTable Implements ILoginIDAL.SelectAdmin
        '实例化
        Dim sqlhelper As New SQLHelper.SqlHelper
        Dim cmdType As CommandType = New CommandType()
        '声明并实例化参数数组
        Dim sqlParams As SqlParameter() = {New SqlParameter("@UserID", AdminInfo.AdminID)}
        Dim cmdtxt As String
        cmdtxt = "select * from Admin_Info where AdminID=@UserID "
        Dim table As New DataTable
        table = sqlhelper.ExecSelect(cmdtxt, CommandType.Text, sqlParams)
        Return table
    End Function
End Class

SqlHelper层

Public Class SqlHelper
    '定义变量     
    '获得数据库连接字符串    
    Private ReadOnly strConnection As String = ConfigurationManager.AppSettings("strConnection")
    '设置连接    
    Dim conn As SqlConnection = New SqlConnection(strConnection)
    '定义cmd 命令    
    Dim cmd As New SqlCommand

    ''' <summary>    
    ''' 执行增删改三个操作,(有参)返回值为Boolean类型,确认是否执行成功    
    ''' </summary>    
    '''<param name="cmdText">需要执行语句,一般是Sql语句,也有存储过程</param>    
    ''' <param name="paras">参数数组,无法确认有多少参数</param>    
    ''' <returns></returns>    
    '''<remarks></remarks>    
    Public Function ExecAddDelUpdate(ByVal cmdText As String, ByVal cmdType As CommandType, ByVal paras As SqlParameter()) As Boolean
        '将传入的值,分别为cmd的属性赋值    
        cmd.Parameters.AddRange(paras)         '将参数传入    
        cmd.CommandType = cmdType              '设置一个值,解释cmdText    
        cmd.Connection = conn                  '设置连接,全局变量     
        cmd.CommandText = cmdText              '设置查询的语句    

        Try
            conn.Open()                      '打开连接    
            Return cmd.ExecuteNonQuery()     '执行增删改操作    
            cmd.Parameters.Clear()          '清除参数    
        Catch ex As Exception
            MsgBox(ex.Message, , "数据库操作") '如果出错,返回0    
            Return False
        Finally
            Call CloseConn(conn)
            Call CloseCmd(cmd)
        End Try
    End Function
    ''' <summary>    
    ''' 执行增删改三个操作,(无参)返回值为Boolean类型,确认是否执行成功    
    ''' </summary>    
    '''<param name="cmdText">需要执行语句,一般是Sql语句,也有存储过程</param>    
    ''' <returns>Interger,受影响的行数</returns>    
    '''<remarks></remarks>    
    Public Function ExecAddDelUpdateNo(ByVal cmdText As String, ByVal cmdType As CommandType) As Boolean
        '为要执行的命令cmd赋值    
        cmd.CommandText = cmdText    '先是查询的sql语句    
        cmd.CommandType = cmdType    '设置Sql语句如何解释    
        cmd.Connection = conn '设置连接    
        '执行操作    
        Try
            conn.Open()
            Return cmd.ExecuteNonQuery()

        Catch ex As Exception
            MsgBox(ex.Message, , "数据库操作") '如果出错,返回0    
            Return False
        Finally
            Call CloseConn(conn)
            Call CloseCmd(cmd)
        End Try
    End Function

    ''' <summary>    
    ''' 执行查询操作,(有参),返回值为datatable类型,参数不限    
    ''' </summary>    
    '''<param name="cmdText">需要执行语句,一般是Sql语句,也有存储过程</param>    
    '''<param name="paras">传入的参数</param>     
    ''' <returns></returns>    
    '''<remarks></remarks>    
    Public Function ExecSelect(ByVal cmdText As String, ByVal cmdType As CommandType, ByVal paras As SqlParameter()) As DataTable

        Dim sqlAdapter As SqlDataAdapter
        Dim dt As New DataTable
        Dim ds As New DataSet

        '给cmd赋值    
        cmd.CommandText = cmdText       '执行的SQL语句
        cmd.CommandType = cmdType         '命名执行类型
        cmd.Connection = conn         '
        cmd.Parameters.AddRange(paras)  '参数添加    
        sqlAdapter = New SqlDataAdapter(cmd)   '实例化adapter    
        Try
            sqlAdapter.Fill(ds)  '用adapter将dataset填充    
            dt = ds.Tables(0)       'datatable为dataSet的第一个表
            cmd.Parameters.Clear()       '清除参数

        Catch ex As Exception
            'MsgBox(" 查询失败", CType(vbOKOnly + MsgBoxStyle.Exclamation, MsgBoxStyle), "警告")    
            MsgBox(ex.Message, , "数据库操作")  '如果出错,返回0    

        Finally
            Call CloseCmd(cmd)    '销毁命令
        End Try
        Return dt

    End Function
    ''' <summary>    
    ''' 执行查询操作,(无参),返回值为datatable类型    
    ''' </summary>    
    '''<param name="cmdText">需要执行语句,一般是Sql语句,也有存储过程</param>    
    '''<param name="cmdType">判断Sql语句的类型,一般都不是存储过程</param>     
    ''' <returns>dataTable,查询到的表格</returns>    
    '''<remarks></remarks>    
    Public Function ExecSelectNo(ByVal cmdText As String, ByVal cmdType As CommandType) As DataTable
        Dim sqlAdapter As SqlDataAdapter
        Dim dt As New DataTable
        Dim ds As New DataSet
        '给cmd赋值    
        cmd.CommandText = cmdText
        cmd.CommandType = cmdType
        cmd.Connection = conn
        sqlAdapter = New SqlDataAdapter(cmd)  '实例化adapter    
        Try
            sqlAdapter.Fill(ds)     '用adapter将dataset填充    
            dt = ds.Tables(0)       'datatable为dataSet的第一个表    
        Catch ex As Exception
            MsgBox(ex.Message, , "数据库操作")  '如果出错,返回0    
        Finally
            Call CloseCmd(cmd)

        End Try
        Return dt
    End Function

    ''' <summary>    
    ''' 关闭连接    
    ''' </summary>    
    '''<param name="conn ">需要关闭的连接</param>    
    '''<remarks></remarks>    
    Public Sub CloseConn(ByVal conn As SqlConnection)
        If (conn.State <> ConnectionState.Closed) Then '如果没有关闭    
            conn.Close()                               '关闭连接    
            conn = Nothing                             '不指向原对象    
        End If
    End Sub
    ''' <summary>    
    ''' 关闭命令    
    ''' </summary>    
    '''<param name="cmd ">需要关闭的命令 </param>    
    '''<remarks></remarks>    
    Public Sub CloseCmd(ByVal cmd As SqlCommand)
        If Not IsNothing(cmd) Then  '如果cmd命令存在    
            cmd.Dispose()           '销毁    
            cmd = Nothing
        End If
    End Sub
End Class

配置文件 : 配置文件要写在UI层的引用中的app.config 内容如下

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <appSettings>
    <add key="DB" value="DAL" />
    <add key="strConnection" value="Server=gao;Database=Charge;User ID=sa;Password=123456" />   
  </appSettings>
</configuration>

各个层之间的引用很重呀!如过你没有引用就会找不到调用的方法,实例化的对象等。会出现很多的问题,正确的各层之间的引用很关键。
开始从UI层开始说吧!
UI层引用Entity层、BLL层、Facade层:
Facade层Entity层、BLL层、IDAL层
BLL层引用Entity层、Factory层、IDAL层:
Factory层:引用IDAL层(用到UI层中的配置文件):
IDAL层引用Entity层:
DAL 层需要引用Entity层、IDAL层、SQLHelper层: