当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET三层架构详解 如何实现三层架构

ASP.NET三层架构详解 如何实现三层架构

2017年12月12日  | 移动技术网IT编程  | 我要评论

日本 林志玲,山西机电职业学院,纽伊斯特

一、数据库

/*==============================================================*/
/* dbms name:   microsoft sql server 2000          */
/*==============================================================*/
 
 
if exists (select 1
      from sysobjects
      where id = object_id('newscontent')
      and  type = 'u')
  drop table newscontent
go
 
 
/*==============================================================*/
/* table: newscontent                      */
/*==============================================================*/
create table newscontent (
  id      int       identity(1,1)  primary key,
  title     nvarchar(50)   not null,
  content    ntext      not null,
  adddate   datetime     not null,
 categoryid  int       not null
)
go
 

 二、项目文件架构

实现步骤为: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

using system;
using system.configuration;
 
namespace utility
{
    /// <summary>
    /// connectioninfo 的摘要说明。
    /// </summary>
    public class connectioninfo
    {
       public static string getsqlserverconnectionstring()
       {
           return configurationsettings.appsettings["sqlconnstring"];
       }
    }
}

2、sqlserverdal项目

(1)sqlhelper.cs抽象类

using system;
using system.data;
using system.data.sqlclient;
using dbutility;
 
namespace sqlserverdal
{
    /// <summary>
    /// sqlhelper 的摘要说明。
    /// </summary>
    public abstract class sqlhelper
    {
       public static readonly string conn_str = connectioninfo.getsqlserverconnectionstring();
 
       /// <summary>
       /// 用提供的函数,执行sql命令,返回一个从指定连接的数据库记录集
       /// </summary>
       /// <remarks>
       /// 例如:
       /// sqldatareader r = executereader(connstring, commandtype.storedprocedure, "publishorders", new sqlparameter("@prodid", 24));
       /// </remarks>
       /// <param name="connectionstring">sqlconnection有效的sql连接字符串</param>
       /// <param name="commandtype">commandtype:commandtype.text、commandtype.storedprocedure</param>
       /// <param name="commandtext">sql语句或存储过程</param>
       /// <param name="commandparameters">sqlparameter[]参数数组</param>
       /// <returns>sqldatareader:执行结果的记录集</returns>
       public static sqldatareader executereader(string connstring, commandtype cmdtype, string cmdtext, params sqlparameter[] cmdparms)
       {
           sqlcommand cmd = new sqlcommand();
           sqlconnection conn = new sqlconnection(connstring);
 
           // 我们在这里用 try/catch 是因为如果这个方法抛出异常,我们目的是关闭数据库连接,再抛出异常,
           // 因为这时不会有datareader存在,此后commandbehaviour.closeconnection将不会工作。
           try
           {
              preparecommand(cmd, conn, null, cmdtype, cmdtext, cmdparms);
              sqldatareader rdr = cmd.executereader(commandbehavior.closeconnection);
              cmd.parameters.clear();
              return rdr;
           }
           catch
           {
              conn.close();
              throw;
           }
       }
 
 
       /// <summary>
       /// 为执行命令做好准备:打开数据库连接,命令语句,设置命令类型(sql语句或存储过程),函数语取。
       /// </summary>
       /// <param name="cmd">sqlcommand 组件</param>
       /// <param name="conn">sqlconnection 组件</param>
       /// <param name="trans">sqltransaction 组件,可以为null</param>
       /// <param name="cmdtype">语句类型:commandtype.text、commandtype.storedprocedure</param>
       /// <param name="cmdtext">sql语句,可以为存储过程</param>
       /// <param name="cmdparms">sql参数数组</param>
       private static void preparecommand(sqlcommand cmd, sqlconnection conn, sqltransaction trans, commandtype cmdtype, string cmdtext, sqlparameter[] cmdparms)
       {
 
           if (conn.state != connectionstate.open)
              conn.open();
 
           cmd.connection = conn;
           cmd.commandtext = cmdtext;
 
           if (trans != null)
              cmd.transaction = trans;
 
           cmd.commandtype = cmdtype;
 
           if (cmdparms != null)
           {
              foreach (sqlparameter parm in cmdparms)
                  cmd.parameters.add(parm);
           }
       }
    }
}

(2)content.cs类

using system;
using system.data;
using system.data.sqlclient;
using model;
using idal;
 
namespace sqlserverdal
{
    /// <summary>
    /// content 的摘要说明。
    /// </summary>
    public class content:icontent 
    {
 
       private const string parm_id = "@id";
       private const string sql_select_content = "select id, title, content, adddate, categoryid from newscontent where id = @id";
 
 
       public contentinfo getcontentinfo(int id)
       {
           //创意文章内容类
           contentinfo ci = null;
 
           //创建一个参数
           sqlparameter parm = new sqlparameter(parm_id, sqldbtype.bigint, 8);
           //赋上id值
           parm.value = id;
 
           using(sqldatareader sdr = sqlhelper.executereader(sqlhelper.conn_str, commandtype.text, sql_select_content, parm))
           {
              if(sdr.read())
              { 
                  ci = new contentinfo(sdr.getint32(0),sdr.getstring(1), sdr.getstring(2),
                     sdr.getdatetime(3), sdr.getint32(4), sdr.getint32(5), sdr.getstring(6));
              }
           }
           return ci;
       }
    }
}



3、model项目

(1)contentinfo.cs

using system;
 
namespace model
{
    /// <summary>
    /// class1 的摘要说明。
    /// </summary>
    public class contentinfo
    {
       private int _id;
       private string _content;
       private string _title;
       private string _from;
       private datetime _adddate;
       private int _clsid;
       private int _tmpid;
 
       /// <summary>
       /// 文章内容构造函数
       /// </summary>
       /// <param name="id">文章流水号id</param>
       /// <param name="content">文章内容</param>
       /// <param name="title">文章标题</param>
       /// <param name="from">文章来源</param>
       /// <param name="clsid">文章的分类属性id</param>
       /// <param name="tmpid">文章的模板属性id</param>
       public contentinfo(int id,string title,string content,string from,datetime adddate,int clsid,int tmpid )
       {
           this._id = id;
           this._content = content;
           this._title = title;
           this._from = from;
           this._adddate = adddate;
           this._clsid = clsid;
           this._tmpid = tmpid;
       }
 
 
       //属性
       public int id
       {
           get  { return _id; }
       }
       public string content
       {
           get  { return _content; }
       }
       public string title
       {
           get  { return _title; }
       }
       public string from
       {
           get  { return _from; }
       }
       public datetime adddate
       {
           get  { return _adddate; }
       }
       public int clsid
       {
           get  { return _clsid; }
       }
       public int tmpid
       {
           get  { return _tmpid; }
       }
 
 
 
    }
}
 

4、idal项目

(1)icontent.cs

using system;
using model;
 
namespace idal
{
    /// <summary>
    /// 文章内容操作接口
    /// </summary>
    public interface icontent
    {
       /// <summary>
       /// 取得文章的内容。
       /// </summary>
       /// <param name="id">文章的id</param>
       /// <returns></returns>
       contentinfo getcontentinfo(int id);
    }
}

5、dalfactory项目

(1)content.cs

using system;
using system.reflection;
using system.configuration;
using idal;
 
namespace dalfactory
{
    /// <summary>
    /// 工产模式实现文章接口。
    /// </summary>
    public class content
    {
       public static idal.icontent create()
       {
           // 这里可以查看 dal 接口类。
           string path = system.configuration.configurationsettings.appsettings["webdal"].tostring();
           string classname = path+".content";
          
           // 用配置文件指定的类组合
           return (idal.icontent)assembly.load(path).createinstance(classname);
       }
    }
}



6、bll项目

(1)content.cs

using system;
 
using model;
using idal;
 
namespace bll
{
    /// <summary>
    /// content 的摘要说明。
    /// </summary>
    public class content
    {
 
       public contentinfo getcontentinfo(int id)
       {
 
           // 取得从数据访问层取得一个文章内容实例
           icontent dal = dalfactory.content.create();
 
           // 用dal查找文章内容
           return dal.getcontentinfo(id);
       }
    }
}

7、web项目

1)、web.config:

 <appsettings> 
<add key="sqlconnstring" value="data source=localhost

;persist security info=true;initial catalog=newsdb;

user id=sa;password= " />
  <add key="webdal" value="sqlserverdal" />  
 </appsettings>

2)、webui.aspx

<%@ page language="c#" codebehind="webui.aspx.cs" autoeventwireup="false" inherits="web.webui" %>
<!doctype html public "-//w3c//dtd html 4.0 transitional//en" >
<html>
    <head>
       <title>webui</title>
       <meta name="generator" content="microsoft visual studio .net 7.1">
       <meta name="code_language" content="c#">
       <meta name="vs_defaultclientscript" content="javascript">
       <meta name="vs_targetschema" content="http://schemas.microsoft.com/intellisense/ie5">
    </head>
    <body ms_positioning="gridlayout">
       <form id="form1" method="post" runat="server">
           <font">宋体"></font>
           <table width="600" border="1">
              <tr>
                  <td style="width: 173px"> </td>
                  <td> 
                     <asp:label id="lbltitle" runat="server"></asp:label></td>
              </tr>
              <tr>
                  <td style="width: 173px; height: 22px"> </td>
                  <td style="height: 22px"> 
                     <asp:label id="lbldatatime" runat="server"></asp:label></td>
              </tr>
              <tr>
                  <td style="width: 173px"> </td>
                  <td> 
                     <asp:label id="lblcontent" runat="server"></asp:label></td>
              </tr>
              <tr>
                  <td style="width: 173px"> </td>
                  <td> </td>
              </tr>
              <tr>
                  <td style="width: 173px; height: 23px"> </td>
                  <td style="height: 23px"> </td>
              </tr>
              <tr>
                  <td style="width: 173px"> </td>
                  <td> </td>
              </tr>
              <tr>
                  <td style="width: 173px"> </td>
                  <td> </td>
              </tr>
              <tr>
                  <td style="width: 173px"> </td>
                  <td> </td>
              </tr>
              <tr>
                  <td style="width: 173px"> </td>
                  <td> 
                     <asp:label id="lblmsg" runat="server">label</asp:label></td>
              </tr>
           </table>
       </form>
    </body>
</html>

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

using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.drawing;
using system.web;
using system.web.sessionstate;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;
 
using bll;
using model;
 
namespace myweb
{
    /// <summary>
    /// webform1 的摘要说明。
    /// </summary>
    public class webui : system.web.ui.page
    {
       protected system.web.ui.webcontrols.label lbltitle;
       protected system.web.ui.webcontrols.label lbldatatime;
       protected system.web.ui.webcontrols.label lblcontent;
       protected system.web.ui.webcontrols.label lblmsg;
 
       private contentinfo ci ;
 
 
       private void page_load(object sender, system.eventargs e)
       {
           if(!page.ispostback)
           {
              getcontent("1");
           }
       }
 
       private void getcontent(string id)
       {
           int id = webcomponents.cleanstring.getint(id);
       
           content c = new content();
           ci = c.getcontentinfo(id);
           if(ci!=null)
           {
              this.lbltitle.text = ci.title;
              this.lbldatatime.text = ci.adddate.tostring("yyyy-mm-dd");
              this.lblcontent.text = ci.content;
           }
           else
           {
              this.lblmsg.text = "没有找到这篇文章";
           }
       }
 
       #region web 窗体设计器生成的代码
       override protected void oninit(eventargs e)
       {
           //
           // codegen: 该调用是 asp.net web 窗体设计器所必需的。
           //
           initializecomponent();
           base.oninit(e);
       }
       
       /// <summary>
       /// 设计器支持所需的方法 - 不要使用代码编辑器修改
       /// 此方法的内容。
       /// </summary>
       private void initializecomponent()
       {  
           this.load += new system.eventhandler(this.page_load);
 
       }
       #endregion
    }
}

4)、webcomponents项目
(1)cleanstring.cs

using system;
using system.text;
 
namespace myweb.webcomponents
{
    /// <summary>
    /// cleanstring 的摘要说明。
    /// </summary>
    public class cleanstring
    {
 
       public static int getint(string inputstring)
       {
           try
           {
              return convert.toint32(inputstring);
           }
           catch
           {
              return 0;
           }
 
       }
 
 
       public static string inputtext(string inputstring, int maxlength)
       {
           stringbuilder retval = new stringbuilder();
 
           // check incoming parameters for null or blank string
           if ((inputstring != null) && (inputstring != string.empty))
           {
              inputstring = inputstring.trim();
 
              //chop the string incase the client-side max length
              //fields are bypassed to prevent buffer over-runs
              if (inputstring.length > maxlength)
                  inputstring = inputstring.substring(0, maxlength);
 
              //convert some harmful symbols incase the regular
              //expression validators are changed
              for (int i = 0; i < inputstring.length; i++)
              {
                  switch (inputstring[i])
                  {
                     case '"':
                         retval.append(""");
                         break;
                     case '<':
                         retval.append("<");
                         break;
                     case '>':
                         retval.append(">");
                         break;
                     default:
                         retval.append(inputstring[i]);
                         break;
                  }
              }
 
              // replace single quotes with white space
              retval.replace("'", " ");
           }
 
           return retval.tostring();
          
       }
        
    }
}

以上就是asp.net三层架构的全部内容,希望对大家的学习有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网