谈谈asp.net三层架构

一、数据库
  1. create table newsContent
  2. (
  3.    ID           int              identity(1,1)   primary key,
  4.    Title          nvarchar(50)     not null,
  5.    Content       ntext            not null,
  6.    AddDate      datetime         not null,
  7.   CategoryID    int              not null
  8. )

二、项目文件架构

 

ID

项目

描述

用途

项目引用关系

实例所需文件

相关方法

1

Web

表现层

Web页和控件

引用BLL

WebUI.aspx

WebUI.aspx.cs

 

GetContent()

2

BLL

业务逻辑层

业务逻辑组件

引用 IDAL,Model,使用DALFactory创建实例

Content.cs

ContentInfo GetContentInfo(int id)

3

IDAL

数据访问层接口定义

每个DAL实现都要实现的一组接口

引用 Model

IContent.cs

ContentInfo GetContentInfo(int id)

4

Model

业务实体

传递各种数据的容器

无引用

ContentInfo.cs

 

5

DALFactory

数据层的抽象工厂

创建反射,用来确定加载哪一个数据库访问程序集的类

引用IDAL,通过读取web.config里设置的程序集,加载类的实例,返回给BLL使用。

Content.cs

IDAL.Icontent create()

6

SQLServerDAL

SQLServer数据访问层

Microsoft SQL Server特定的Pet Shop DAL实现,使用了IDAL接口

引用 Model和IDAL,被DALFactory加载的程序集,实现接口里的方法。

SqlHelper.cs

 

 

 

Content.cs

SqlDataReader ExecuteReader()

PrepareCommand()

ContentInfo GetContentInfo(int id)

OracleDAL

Oracle数据访问层

7

DBUtility

数据库访问组件基础类

GetSqlServerConnectionString得到数据库连接字符串,也可省去该项目,在SQLServerDAL.SqlHelper中用static readonly string SqlConnectionString代替。

无引用

 

 

实现步骤为:4-3-6-5-2-1

 

实现步骤过程

1、创建Model,实现业务实体。
2、创建IDAL,实现接口。
3、创建SQLServerDAL,实现接口里的方法。
4、增加web.config里的配置信息,为SQLServerDAL的程序集。
5、创建DALFactory,返回程序集的指定类的实例。
6、创建BLL,调用DALFactory,得到程序集指定类的实例,完成数据操作方法。
7、创建WEB,调用BLL里的数据操作方法。

注意:

1、web.config里的程序集名称必须与SQLServerDAL里的输出程序集名称一致。
2、DALFactory里只需要一个DataAccess类,可以完成创建所有的程序集实例。
3、项目创建后,注意修改各项目的默认命名空间和程序集名称。
4、注意修改解决方案里的项目依赖。
5、注意在解决方案里增加各项目引用。

 

三、各层间的访问过程

1、传入值,将值进行类型转换(为整型)。
2、创建BLL层的content.cs对象c,通过对象c访问BLL层的方法GetContentInfo(ID)调用BLL层。
3、BLL层方法GetContentInfo(ID)中取得数据访问层SQLServerDAL的实例,实例化IDAL层的接口对象dal,这个对象是由工厂层DALFactory创建的,然后返回IDAL层传入值所查找的内容的方法dal.GetContentInfo(id)。
4、数据工厂通过web.config配置文件中给定的webdal字串访问SQLServerDAL层,返回一个完整的调用SQLServerDAL层的路径给 BLL层
5、到此要调用SQLServerDAL层,SQLServerDAL层完成赋值Model层的对象值为空,给定一个参数,调用SQLServerDAL层的SqlHelper的ExecuteReader方法,读出每个字段的数据赋值给以定义为空的Model层的对象。
6、SqlHelper执行sql命令,返回一个指定连接的数据库记录集,在这里需要引用参数类型,提供为打开连接命令执行做好准备PrepareCommand。
7、返回Model层把查询得到的一行记录值赋值给SQLServerDAL层的引入的Model层的对象ci,然后把这个对象返回给BLL。
8、回到Web层的BLL层的方法调用,把得到的对象值赋值给Lable标签,在前台显示给界面

 

四、项目中的文件清单

1、DBUtility项目

(1)connectionInfo.cs

  1. using System;
  2. using System.Configuration;
  3. namespace Utility
  4. {
  5.        /// <summary>
  6.        /// ConnectionInfo 的摘要说明。
  7.        /// </summary>
  8.        public class ConnectionInfo
  9.        {
  10.               public static string GetSqlServerConnectionString()
  11.               {
  12.                      return ConfigurationSettings.AppSettings["SQLConnString"];
  13.               }
  14.        }
  15. }

2、SQLServerDAL项目

(1)SqlHelper.cs抽象类

  1. using System;
  2. using System.Data;
  3. using System.Data.SqlClient;
  4. using DBUtility;
  5. namespace SQLServerDAL
  6. {
  7.        /// <summary>
  8.        /// SqlHelper 的摘要说明。
  9.        /// </summary>
  10.        public abstract class SqlHelper
  11.        {
  12.               public static readonly string CONN_STR = ConnectionInfo.GetSqlServerConnectionString();
  13.               /// <summary>
  14.               /// 用提供的函数,执行SQL命令,返回一个从指定连接的数据库记录集
  15.               /// </summary>
  16.               /// <remarks>
  17.               /// 例如:
  18.               /// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  19.               /// </remarks>
  20.               /// <param name="connectionString">SqlConnection有效的SQL连接字符串</param>
  21.               /// <param name="commandType">CommandType:CommandType.Text、CommandType.StoredProcedure</param>
  22.               /// <param name="commandText">SQL语句或存储过程</param>
  23.               /// <param name="commandParameters">SqlParameter[]参数数组</param>
  24.               /// <returns>SqlDataReader:执行结果的记录集</returns>
  25.               public static SqlDataReader ExecuteReader(string connString, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms)
  26.               {
  27.                      SqlCommand cmd = new SqlCommand();
  28.                      SqlConnection conn = new SqlConnection(connString);
  29.                      // 我们在这里用 try/catch 是因为如果这个方法抛出异常,我们目的是关闭数据库连接,再抛出异常,
  30.                      // 因为这时不会有DataReader存在,此后commandBehaviour.CloseConnection将不会工作。
  31.                      try
  32.                      {
  33.                             PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
  34.                             SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  35.                             cmd.Parameters.Clear();
  36.                             return rdr;
  37.                      }
  38.                      catch
  39.                      {
  40.                             conn.Close();
  41.                             throw;
  42.                      }
  43.               }
  44.               /// <summary>
  45.               /// 为执行命令做好准备:打开数据库连接,命令语句,设置命令类型(SQL语句或存储过程),函数语取。
  46.               /// </summary>
  47.               /// <param name="cmd">SqlCommand 组件</param>
  48.               /// <param name="conn">SqlConnection 组件</param>
  49.               /// <param name="trans">SqlTransaction 组件,可以为null</param>
  50.               /// <param name="cmdType">语句类型:CommandType.Text、CommandType.StoredProcedure</param>
  51.               /// <param name="cmdText">SQL语句,可以为存储过程</param>
  52.               /// <param name="cmdParms">SQL参数数组</param>
  53.               private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
  54.               {
  55.                      if (conn.State != ConnectionState.Open)
  56.                             conn.Open();
  57.                      cmd.Connection = conn;
  58.                      cmd.CommandText = cmdText;
  59.                      if (trans != null)
  60.                             cmd.Transaction = trans;
  61.                      cmd.CommandType = cmdType;
  62.                      if (cmdParms != null)
  63.                      {
  64.                             foreach (SqlParameter parm in cmdParms)
  65.                                    cmd.Parameters.Add(parm);
  66.                      }
  67.               }
  68.        }
  69. }

(2)Content.cs类

  1. using System;
  2. using System.Data;
  3. using System.Data.SqlClient;
  4. using Model;
  5. using IDAL;
  6. namespace SQLServerDAL
  7. {
  8.        /// <summary>
  9.        /// Content 的摘要说明。
  10.        /// </summary>
  11.        public class Content:IContent 
  12.        {
  13.               private const string PARM_ID = "@ID";
  14.               private const string SQL_SELECT_CONTENT = "Select ID, Title, Content, AddDate, CategoryID From newsContent Where ID = @ID";
  15.               public ContentInfo GetContentInfo(int id)
  16.               {
  17.                      //创意文章内容类
  18.                      ContentInfo ci = null;
  19.                      //创建一个参数
  20.                      SqlParameter parm = new SqlParameter(PARM_ID, SqlDbType.BigInt, 8);
  21.                      //赋上ID值
  22.                      parm.Value = id;
  23.                      using(SqlDataReader sdr = SqlHelper.ExecuteReader(SqlHelper.CONN_STR, CommandType.Text, SQL_SELECT_CONTENT, parm))
  24.                      {
  25.                             if(sdr.Read())
  26.                             { 
  27.                                    ci = new ContentInfo(sdr.GetInt32(0),sdr.GetString(1), sdr.GetString(2),    sdr.GetDateTime(3), sdr.GetInt32(4), sdr.GetInt32(5), sdr.GetString(6));
  28.                             }
  29.                      }
  30.                      return ci;
  31.               }
  32.        }
  33. }

 

3、Model项目

(1)contentInfo.cs

  1. using System;
  2. namespace Model
  3. {
  4.        /// <summary>
  5.        /// Class1 的摘要说明。
  6.        /// </summary>
  7.        public class ContentInfo
  8.        {
  9.               private int _ID;
  10.               private string _Content;
  11.               private string _Title;
  12.               private string _From;
  13.               private DateTime _AddDate;
  14.               private int _clsID;
  15.               private int _tmpID;
  16.               /// <summary>
  17.               /// 文章内容构造函数
  18.               /// </summary>
  19.               /// <param name="id">文章流水号ID</param>
  20.               /// <param name="content">文章内容</param>
  21.               /// <param name="title">文章标题</param>
  22.               /// <param name="from">文章来源</param>
  23.               /// <param name="clsid">文章的分类属性ID</param>
  24.               /// <param name="tmpid">文章的模板属性ID</param>
  25.               public ContentInfo(int id,string title,string content,string from,DateTime addDate,int clsid,int tmpid )
  26.               {
  27.                      this._ID = id;
  28.                      this._Content = content;
  29.                      this._Title = title;
  30.                      this._From = from;
  31.                      this._AddDate = addDate;
  32.                      this._clsID = clsid;
  33.                      this._tmpID = tmpid;
  34.               }
  35.               //属性
  36.               public int ID
  37.               {
  38.                      get   { return _ID; }
  39.               }
  40.               public string Content
  41.               {
  42.                      get   { return _Content; }
  43.               }
  44.               public string Title
  45.               {
  46.                      get   { return _Title; }
  47.               }
  48.               public string From
  49.               {
  50.                      get   { return _From; }
  51.               }
  52.               public DateTime AddDate
  53.               {
  54.                      get   { return _AddDate; }
  55.               }
  56.               public int ClsID
  57.               {
  58.                      get   { return _clsID; }
  59.               }
  60.               public int TmpID
  61.               {
  62.                      get   { return _tmpID; }
  63.               }
  64.        }
  65. }

 

 

4、IDAL项目

(1)Icontent.cs

  1. using System;
  2. using Model;
  3. namespace IDAL
  4. {
  5.        /// <summary>
  6.        /// 文章内容操作接口
  7.        /// </summary>
  8.        public interface IContent
  9.        {
  10.               /// <summary>
  11.               /// 取得文章的内容。
  12.               /// </summary>
  13.               /// <param name="id">文章的ID</param>
  14.               /// <returns></returns>
  15.               ContentInfo GetContentInfo(int id);
  16.        }
  17. }

 

5、DALFactory项目

(1)Content.cs

  1. using System;
  2. using System.Reflection;
  3. using System.Configuration;
  4. using IDAL;
  5. namespace DALFactory
  6. {
  7.        /// <summary>
  8.        /// 工产模式实现文章接口。
  9.        /// </summary>
  10.        public class Content
  11.        {
  12.               public static IDAL.IContent Create()
  13.               {
  14.                      // 这里可以查看 DAL 接口类。
  15.                      string path = System.Configuration.ConfigurationSettings.AppSettings["WebDAL"].ToString();
  16.                      string className = path+".Content";// 用配置文件指定的类组合
  17.                      return (IDAL.IContent)Assembly.Load(path).CreateInstance(className);
  18.               }
  19.        }
  20. }

 

6、BLL项目

(1)Content.cs

  1. using System;
  2. using Model;
  3. using IDAL;
  4. namespace BLL
  5. {
  6.        /// <summary>
  7.        /// Content 的摘要说明。
  8.        /// </summary>
  9.        public class Content
  10.        {
  11.               public ContentInfo GetContentInfo(int id)
  12.               {
  13.                      // 取得从数据访问层取得一个文章内容实例
  14.                      IContent dal = DALFactory.Content.Create();
  15.                      // 用DAL查找文章内容
  16.                      return dal.GetContentInfo(id);
  17.               }
  18.        }
  19. }

 

7、Web项目

1、Web.config:

  1. <appSettings>
  2.   <add key="SQLConnString" value="Data Source=localhost;Persist Security info=True;Initial Catalog=newsDB;User ID=sa;Password= " />
  3.   <add key="WebDAL" value="SQLServerDAL" />   
  4. </appSettings>

2、WebUI.aspx

  1. <%@ Page language="c#" Codebehind="WebUI.aspx.cs" AutoEventWireup="false" Inherits="Web.WebUI" %>
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
  3. <HTML>
  4.        <HEAD>
  5.               <title>WebUI</title>
  6.               <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  7.               <meta name="CODE_LANGUAGE" Content="C#">
  8.               <meta name="vs_defaultClientScript" content="JavaScript">
  9.               <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  10.        </HEAD>
  11.        <body MS_POSITIONING="GridLayout">
  12.               <form id="Form1" method="post" runat="server">
  13.                      <FONT">宋体"></FONT>
  14.                      <table width="600" border="1">
  15.                             <tr>
  16.                                    <td style="WIDTH: 173px"> </td>
  17.                                    <td> 
  18.                                           <asp:Label id="lblTitle" runat="server"></asp:Label></td>
  19.                             </tr>
  20.                             <tr>
  21.                                    <td style="WIDTH: 173px; HEIGHT: 22px"> </td>
  22.                                    <td style="HEIGHT: 22px"> 
  23.                                           <asp:Label id="lblDataTime" runat="server"></asp:Label></td>
  24.                             </tr>
  25.                             <tr>
  26.                                    <td style="WIDTH: 173px"> </td>
  27.                                    <td> 
  28.                                           <asp:Label id="lblContent" runat="server"></asp:Label></td>
  29.                             </tr>
  30.                             <tr>
  31.                                    <td style="WIDTH: 173px"> </td>
  32.                                    <td> </td>
  33.                             </tr>
  34.                             <tr>
  35.                                    <td style="WIDTH: 173px; HEIGHT: 23px"> </td>
  36.                                    <td style="HEIGHT: 23px"> </td>
  37.                             </tr>
  38.                             <tr>
  39.                                    <td style="WIDTH: 173px"> </td>
  40.                                    <td> </td>
  41.                             </tr>
  42.                             <tr>
  43.                                    <td style="WIDTH: 173px"> </td>
  44.                                    <td> </td>
  45.                             </tr>
  46.                             <tr>
  47.                                    <td style="WIDTH: 173px"> </td>
  48.                                    <td> </td>
  49.                             </tr>
  50.                             <tr>
  51.                                    <td style="WIDTH: 173px"> </td>
  52.                                    <td> 
  53.                                           <asp:Label id="lblMsg" runat="server">Label</asp:Label></td>
  54.                             </tr>
  55.                      </table>
  56.               </form>
  57.        </body>
  58. </HTML>

3、WebUI.aspx.cs后台调用显示:

  1. using System;
  2. using System.Collections;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Web;
  7. using System.Web.SessionState;
  8. using System.Web.UI;
  9. using System.Web.UI.WebControls;
  10. using System.Web.UI.HtmlControls;
  11. using BLL;
  12. using Model;
  13. namespace myWeb
  14. {
  15.        /// <summary>
  16.        /// WebForm1 的摘要说明。
  17.        /// </summary>
  18.        public class WebUI : System.Web.UI.Page
  19.        {
  20.               protected System.Web.UI.WebControls.Label lblTitle;
  21.               protected System.Web.UI.WebControls.Label lblDataTime;
  22.               protected System.Web.UI.WebControls.Label lblContent;
  23.               protected System.Web.UI.WebControls.Label lblMsg;
  24.               private ContentInfo ci ;
  25.               private void Page_Load(object sender, System.EventArgs e)
  26.               {
  27.                      if(!Page.IsPostBack)
  28.                      {
  29.                             GetContent("1");
  30.                      }
  31.               }
  32.               private void GetContent(string id)
  33.               {
  34.                      int ID = WebComponents.CleanString.GetInt(id);         
  35.                      Content c = new Content();
  36.                      ci = c.GetContentInfo(ID);
  37.                      if(ci!=null)
  38.                      {
  39.                             this.lblTitle.Text = ci.Title;
  40.                             this.lblDataTime.Text = ci.AddDate.ToString("yyyy-MM-dd");
  41.                             this.lblContent.Text = ci.Content;
  42.                      }
  43.                      else
  44.                      {
  45.                             this.lblMsg.Text = "没有找到这篇文章";
  46.                      }
  47.               } 
  48.               #region Web 窗体设计器生成的代码
  49.               override protected void OnInit(EventArgs e)
  50.               {
  51.                      //
  52.                      // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
  53.                      //
  54.                      InitializeComponent();
  55.                      base.OnInit(e);
  56.               }
  57.           
  58.               /// <summary>
  59.               /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  60.               /// 此方法的内容。
  61.               /// </summary>
  62.               private void InitializeComponent()
  63.               {   
  64.                      this.Load += new System.EventHandler(this.Page_Load);
  65.               }
  66.               #endregion
  67.        }
  68. }

4、WebComponents项目

(1)CleanString.cs

  1. using System;
  2. using System.Text;
  3. namespace myWeb.WebComponents
  4. {
  5.        /// <summary>
  6.        /// CleanString 的摘要说明。
  7.        /// </summary>
  8.        public class CleanString
  9.        {
  10.               public static int GetInt(string inputString)
  11.               {
  12.                      try
  13.                      {
  14.                             return Convert.ToInt32(inputString);
  15.                      }
  16.                      catch
  17.                      {
  18.                             return 0;
  19.                      }
  20.               }
  21.               public static string InputText(string inputString, int maxLength)
  22.               {
  23.                      StringBuilder retVal = new StringBuilder();
  24.                      // check incoming parameters for null or blank string
  25.                      if ((inputString != null) && (inputString != String.Empty))
  26.                      {
  27.                             inputString = inputString.Trim();
  28.                             //chop the string incase the client-side max length
  29.                             //fields are bypassed to prevent buffer over-runs
  30.                             if (inputString.Length > maxLength)
  31.                                    inputString = inputString.Substring(0, maxLength);
  32.                             //convert some harmful symbols incase the regular
  33.                             //expression validators are changed
  34.                             for (int i = 0; i < inputString.Length; i++)
  35.                             {
  36.                                    switch (inputString[i])
  37.                                    {
  38.                                           case '"':
  39.                                                  retVal.Append(""");
  40.                                                  break;
  41.                                           case '<':
  42.                                                  retVal.Append("<");
  43.                                                  break;
  44.                                           case '>':
  45.                                                  retVal.Append(">");
  46.                                                  break;
  47.                                           default:
  48.                                                  retVal.Append(inputString[i]);
  49.                                                  break;
  50.                                    }
  51.                             }
  52.                             // Replace single quotes with white space
  53.                             retVal.Replace("'"" ");
  54.                      }
  55.                      return retVal.ToString();                
  56.               }              
  57.        }
  58. }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值