zoukankan      html  css  js  c++  java
  • ASP.NET MVC+Spring.net+Nhibernate

        第八步:Asp.NET MVC引入的DLL文件
    
    (1) 通过上面的准备工作,可以说是我们的大部分基层代码的书写任务都已经完成了,下面才是本项目值得学习的地方,我们全部在MVC新建的项目中书写代码,因为这里用到了Spring.net,Nhibernate,MVC,easyUI等,所以非常值得我们去研究,当然我的写法可能也有问题,希望我们可以交流,这样我们可以共同进步。
    
    (2) 因为用到了Nhibernate,Spring.net,所以我将引入的DLL文件的截图先放在这里吧,当然,我的项目中有dll文件夹,这样将这里面的DLL全部引入项目中即可。
    
     
    
        第九步:书写XML,实现Spring.net,Nhibernate
    
    (1) 首先我们在ASP.NET MVC新建的项目NewKJ241项目下面新建三个XML,命名各为:CommonDao.xml,HibernateDaos.xml,Services.xml,其中三个XML的作用各是什么,我们下面解释一下:
    
     1) CommonDao.xml的作用是定义Spring.net实现数据库的节点,里面包含了NHibernate和数据库的配置文件,引用了Spring.net提供的HibernateTemplate模板,方便和数据库的交互等,和创建事物的节点(TransactionInterceptor声明式事物配置)等。是最为重要的一个XML节点,而且在这个XML中我都详细的注释了所有节点的作用,这样我们可以很快的熟悉这些代码到底是干什么的,代码如下:
    
    <?xml version="1.0" encoding="utf-8" ?>
    
    <objects xmlns="http://www.springframework.net"
    
             xmlns:db="http://www.springframework.net/database">
    
      <!-- Database and NHibernate Configuration这下面是配置使用Nhibernate,在这里使用到了连接池-->
    
      <db:provider id="DbProvider"
    
                                          provider="SqlServer-2.0"
    
                                          connectionString="server=.;database=bkj241;uid=sa;pwd=saa;Min Pool Size=10;Max Pool Size=50;Connect Timeout=30" />
    
      <!--定义Session工厂,查找<db:provider />节点下面的链接字符串-->
    
      <!--也可以写成type="Xino.Spring.DecryptLocalSessionFactoryObject, Xino.Core.Spring",因为继承自Spring.Data.NHibernate.LocalSessionFactoryObject,这个类主要用来配置SessionFactory -->
    
           <object id="SessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate12">
    
                  <property name="DbProvider" ref="DbProvider" />
    
                  <property name="MappingAssemblies">
    
                         <list>
    
                                <!--这是配置嵌入资源的xx类对应的xx.hbm.xml文件所在的项目名称-->
    
                                <value>NewKJ241.Model</value>
    
                         </list>
    
                  </property>
    
        <!-- Nhibernate数据库的配置文件-->
    
                  <property name="HibernateProperties">
    
                         <dictionary>
    
                                <entry key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
    
                                <entry key="hibernate.dialect" value="NHibernate.Dialect.MsSql2005Dialect" />
    
                                <entry key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
    
                                <entry key="show_sql" value="true" />
    
                         </dictionary>
    
     
    
          <!--当需要启用二级缓存的时候使用,NHibernate.Cache.HashtableCacheProvider类是NHibernate默认的缓冲处理器-->
    
          <!--<entry key="cache.provider_class" value="NHibernate.Cache.HashtableCacheProvider"/>
    
          <entry key="cache.use_second_level_cache" value="false"/>
    
          <entry key="cache.use_query_cache" value="true"/>-->
    
     
    
        </property>
    
        <!-- 控制方法的读写属性 -->
    
        <!--<property name="EntityCacheStrategies">
    
          <object type="Spring.Util.Properties">
    
            --><!--其中这里的value可以为read-write,read-only,nonstrict-read-write,transactional,
    
            分别代表的意思是:
    
            read-only:只读缓存。适用于只读数据,可用于群集中。
    
            read-write:读写缓存。
    
            nonstrict-read-write:非严格读写缓存,不保证缓存与数据库的一致性。
    
            transactional:事务缓存。提供可重复读的事务隔离级别。--><!--     
    
            <property name="['NewKJ241,NewKJ241.Model']" value="read-write"/>
    
          </object>
    
        </property>
    
        <property name="ExposeTransactionAwareSessionFactory" value="true" />-->
    
      </object>
    
     
    
      <!--HibernateTemplate只是提供了一个模板,方便和数据库交互,而HibernateTransactionManager是一个事物管理器, -->
    
           <object id="HibernateTransactionManager" type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate12">
    
                  <property name="DbProvider" ref="DbProvider" />
    
                  <property name="sessionFactory" ref="SessionFactory" />
    
           </object>
    
     
    
      <!-- Spring.net使用TransactionInterceptor声明式事物配置-->
    
           <object id="TransactionInterceptor" type="Spring.Transaction.Interceptor.TransactionInterceptor, Spring.Data">
    
                  <property name="TransactionManager" ref="HibernateTransactionManager" />
    
                  <property name="TransactionAttributeSource">
    
                         <object type="Spring.Transaction.Interceptor.AttributesTransactionAttributeSource, Spring.Data" />
    
                  </property>
    
           </object>
    
    </objects>2) HibernateDaos.xml的作用是调用KJ241.HibernateDao类库里面定义的类所实现的方法,在这里要注意一下泛型,如果你的项目中没有使用泛型的话这段代码需要修改的,我的项目中使用了泛型,所以这段代码如下:
    
    <?xml version="1.0" encoding="utf-8" ?>
    
    <objects xmlns="http://www.springframework.net"
    
             xmlns:db="http://www.springframework.net/database">
    
      <!--调用KJ241.HibernateDao类库里面定义的类所实现的方法,下面的写法可以实现泛型-->
    
      <object id="UserDepInfoDao"   type="NewKJ241.NHibernateDao.UserDepInfoDao&lt;NewKJ241.Model.UserDepInfo>,NewKJ241.NHibernateDao">
    
                  <property name="SessionFactory" ref="SessionFactory" />
    
           </object>
    
    </objects>3) Services.xml的作用是映射HibernateDaos.xml里面的节点属性,这段代码的作用是使用事物管理器实现项目实现功能的只读或者只写属性等。详细的解释在XML里面都有,代码如下:
    
    <?xml version="1.0" encoding="utf-8" ?>
    
    <objects xmlns="http://www.springframework.net"
    
             xmlns:db="http://www.springframework.net/database">
    
      <!--调用HibernateDaos.xml里面的 -->
    
      <object id="UserDepInfoService" parent="BaseTransactionManager">
    
        <!-- 如果使用这个事物管理器的话,必须在这里加上节点parent="BaseTransactionManager"-->
    
        <property name="Target">
    
          <object type="NewKJ241.BLL.UserDepInfoBLL&lt;NewKJ241.Model.UserDepInfo>,NewKJ241.BLL">
    
            <property name="UserDepInfoDao" ref="UserDepInfoDao"/>
    
          </object>
    
        </property>
    
      </object>
    
     
    
      <!--事物处理策略,本地数据库事物-->
    
      <object id="transactionManager"
    
            type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate12">
    
        <property name="DbProvider" ref="DbProvider"/>
    
        <property name="SessionFactory" ref="SessionFactory"/>
    
      </object>
    
     
    
      <!--事物管理器,这里是判断了这些实现的方法的操作,如果不写的话,在实现这些方法的时候就会出现错误-->
    
      <object id="BaseTransactionManager"  type="Spring.Transaction.Interceptor.TransactionProxyFactoryObject, Spring.Data" abstract="true">
    
        <property name="PlatformTransactionManager" ref="transactionManager"/>
    
        <property name="TransactionAttributes">
    
          <name-values>
    
            <!--增加-->
    
            <add key="Save*" value="PROPAGATION_REQUIRED"/>
    
            <!--修改-->
    
            <add key="Update*" value="PROPAGATION_REQUIRED"/>
    
            <!--删除-->
    
            <add key="Delete*" value="PROPAGATION_REQUIRED"/>
    
            <!--获取-->
    
            <add key="Get*" value="PROPAGATION_REQUIRED"/>
    
            <!--浏览-->
    
            <add key="Find*" value="PROPAGATION_SUPPORTS,readOnly"/>
    
            <!--检索-->
    
            <add key="Search*" value="PROPAGATION_SUPPORTS,readOnly"/>
    
            <!--报表-->
    
            <add key="Query*" value="PROPAGATION_SUPPORTS,readOnly"/>
    
            <!--载入-->
    
            <add key="Load*" value="PROPAGATION_SUPPORTS,readOnly"/>
    
            <!--报表-->
    
            <add key="Report*" value="PROPAGATION_SUPPORTS,readOnly"/>
    
            <!--其它-->
    
            <add key="*" value="PROPAGATION_REQUIRED"/>
    
          </name-values>
    
        </property>
    
      </object>
    
    </objects>
    
    
     
    
    (2) 这样的话我们的Spring.net,Nhibernate映射前面我们建立的接口和方法的类库所实现的功能都就差不多了,这单个XML文件还值得我们仔细的研究,举一反三吗!!
    
        第十步:配置Web.Config
    
    (1) 当我们完成了前面所有的工作后,我们就要开始配置我们的WebConfig文件了,在webConfig里面我们需要加入的代码如下:
    <configSections>
    
        <!--Web.Config的配置文件-->
    
        <!--Spring.net里面的log4net的使用,log4net是一个开源的日志记录组件, -->
    
                  <sectionGroup name="spring">
    
                         <section name="context" type="Spring.Context.Support.WebContextHandler, Spring.Web"/>
    
                         <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
    
                         <section name="parsers" type="Spring.Context.Support.NamespaceParsersSectionHandler, Spring.Core"/>
    
                  </sectionGroup>
    
                  <section name="SpringOverrideProperty" type="System.Configuration.NameValueSectionHandler"/>
    
           </configSections>
    
           <!--可以注释-->
    
      <SpringOverrideProperty>
    
                  <add key="NamingStrategy.TableHead" value=""/>
    
                  <add key="db.datasource" value="server=.;uid=sa;pwd=saa;database=bkj241;"/>
    
                  <!-- 0 to 6 (1 Debug 4 Error)-->
    
                  <add key="SystemInit.IsDebug" value="true"/>
    
                  <add key="SystemInit.Level" value="4"/>
    
           </SpringOverrideProperty>
    
           <spring>
    
                  <parsers>
    
                         <parser type="Spring.Data.Config.DatabaseNamespaceParser, Spring.Data"/>
    
                         <parser type="Spring.Transaction.Config.TxNamespaceParser, Spring.Data"/>
    
                  </parsers>
    
                  <context>
    
          <!--寻找定义的XML文件 -->
    
                         <resource uri="~/Configs/CommonDao.xml"/>
    
                         <resource uri="~/Configs/HibernateDaos.xml"/>
    
                         <resource uri="~/Configs/Services.xml"/>
    
                  </context>
    
           </spring>
    
    然后在<system.web>节点下面写入代码如下:
    
        <!--根据请求中指定的 URL 和 HTTP 谓词将传入的请求映射到相应的处理程序。可以在配置层次中的任何级别声明此元素。-->
    
            <httpHandlers>
    
                    <add verb="*" path="*.aspx" type="Spring.Web.Support.PageHandlerFactory, Spring.Web"/>
    
                    <add verb="*" path="*.mvc" validate="false" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"/>
    
             </httpHandlers>
    
             <httpModules>
    
                    <add name="OpenSessionInView" type="Spring.Data.NHibernate.Support.OpenSessionInViewModule, Spring.Data.NHibernate12"/>
    
                    <add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"/>
    
             </httpModules>
    
    复制代码
    
     
    
    (2) 这样我们的WebConfig配置文件已经配置成功了,可能配置的时候会出现什么错误,那我们稍微的改改就OK了,下面就是项目界面的实现
    
        第十一步:HomeController控制器的书写
    
    (1) 当我们完成上面的所有的配置的时候,可以说我们的项目已经完成的差不多了,这里我们将MVC自动生成的HomeController控制器删除,我们重新创建一个HomeController控制器,在控制器中实现我们要对数据的所有操作的方法的代码,下面我就直接贴出代码了,代码下面都有注释的!!
    复制代码
    
         public UserDepInfo entity = null;
    
     
    
            private IUserDepInfoBLL<UserDepInfo> userDepInfoService;
    
     
    
            public IUserDepInfoBLL<UserDepInfo> UserDepInfoService
    
            {
    
                get { return this.userDepInfoService; }
    
                set { this.userDepInfoService = value; }
    
            }
    
     
    
            public ActionResult Index()
    
            {
    
                return View();
    
            }
    
     
    
            //
    
            private void Connection_KJ241()
    
            {
    
                var webApplicationContext = ContextRegistry.GetContext() as WebApplicationContext;
    
               
    
                UserDepInfoService =
    
                    webApplicationContext.GetObject("UserDepInfoService") as IUserDepInfoBLL<UserDepInfo>;
    
            }
    
     
    
            //实现所有信息的显示和条件查询
    
            public ActionResult LoadAllByPage(int page, int rows, string order, string sort, string DepName)
    
            {
    
                Connection_KJ241();
    
                long total = 0;
    
                //Select将序列中的每一个新元素投影到新表中
    
                var list = this.UserDepInfoService.LoadAllByPage(out total, page, rows, order, sort, DepName).Select(entity => new
    
                {
    
                    entity.Id,
    
                    entity.DepID,
    
                    entity.DepName
    
                });
    
     
    
                var result = new { total = total, rows = list.ToList() };
    
     
    
                return Json(result);
    
            }
    
     
    
            public ActionResult Save(UserDepInfo entity)
    
            {
    
                Connection_KJ241();
    
                if (entity.Id == 0)
    
                {
    
                    this.UserDepInfoService.Save(entity);
    
                }
    
                return Json(new { success = true, Message = "保存成功" }, "text/html", JsonRequestBehavior.AllowGet);
    
            }
    
     
    
            public ActionResult Delete(string idList)
    
            {
    
                Connection_KJ241();
    
                this.UserDepInfoService.Delete(idList);
    
                //提示删除信息成功,如果在这里的idList得到的数据时0的话,又会执行本操作的
    
                var result = new { success = true, Message = "删除成功!" };
    
                return Json(result);
    
            }
    
     
    
            public ActionResult Update(int Id, UserDepInfo entity)
    
            {
    
                Connection_KJ241();
    
                var model = this.UserDepInfoService.Get(Id);
    
                //model.DepID = int.Parse(Request["DepId"].ToString());
    
                //model.DepName = Request["DepName"].ToString();
    
                model.DepID = entity.DepID;
    
                model.DepName = entity.DepName;
    
                this.UserDepInfoService.Update(model);
    
     
    
                return Json(new { success = true, Message = "保存成功" }, "text/html", JsonRequestBehavior.AllowGet);
    
            }
    
     
    
            public ActionResult Login()
    
            {
    
                ViewData["entity"] = "欢迎光临";
    
                return View();
    
            }
    
    复制代码
    
     
    
       
    
    (2) 接下来我们在控制器中Index方法下面添加视图,创建一个前台页面Index,在Index页面书写前台显示的HTML代码等,在这里我们就要用到easyUI了,所以我们要将我们项目的easyUI类库全部应用到我们需要的地方,代码如下:
     
    复制代码
    
    <head runat="server">
    
        <title>Index</title>
    
        <!--引用所有的Jquery,easyUI文件 !-->
    
        <link rel="stylesheet" type="text/css" href="http://www.cnblogs.com/easyui/themes/default/easyui.css" />
    
           <link rel="stylesheet" type="text/css" href="http://www.cnblogs.com/easyui/themes/icon.css" />
    
        <script type="text/javascript" src="http://www.cnblogs.com/Scripts/jquery-1.4.1.min.js"></script>
    
           <script type="text/javascript" src="http://www.cnblogs.com/easyui/jquery.easyui.min.js"></script>
    
        <script type="text/javascript" src="http://www.cnblogs.com/easyui/locale/easyui-lang-zh_CN.js"></script>
    
            <style type="text/css">
    
                  #fm{
    
                         margin:0;
    
                         padding:10px 30px;
    
                  }
    
                  .ftitle{
    
                         font-size:14px;
    
                         font-weight:bold;
    
                         color:#666;
    
                         padding:5px 0;
    
                         margin-bottom:10px;
    
                         border-bottom:1px solid #ccc;
    
                  }
    
                  .fitem{
    
                         margin-bottom:5px;
    
                  }
    
                  .fitem label{
    
                         display:inline-block;
    
                         80px;
    
                  }
    
           </style>
    
           <script type="text/javascript">
    
            //条件查询
    
               function check() {
    
                   var keywords = $("#SSID").val();
    
                   $('#dg').datagrid('load', {
    
                       DepName: keywords
    
                   });
    
               }
    
            //添加信息
    
               var url;
    
               function newUser() {
    
                   $('#dlg').dialog('open').dialog('setTitle', '添加');
    
                   $('#fm').form('clear');
    
                   url = '/Home/Save/';
    
               }
    
     
    
            //修改信息
    
               function editUser() {
    
                   var row = $('#dg').datagrid('getSelections');
    
                   if (row.length == 1) {
    
                       if (row[0]) {
    
                           $('#dlg').dialog('open').dialog('setTitle', '修改');
    
                           $('#fm').form('load', row[0]);
    
                           url = '/Home/Update/' + row.Id;
    
                       }
    
                   } else {
    
                       $.messager.alert("提示", "每次只能修改一条,请重选");
    
                       return;
    
                   }
    
               }
    
     
    
               function saveUser() {
    
                   $('#fm').form('submit', {
    
                       url: url,
    
                       onSubmit: function () {
    
                           return $(this).form('validate');
    
                       },
    
                       success: function (result) {
    
                           var result = eval('(' + result + ')');
    
                           if (result.success) {
    
                               $('#dlg').dialog('close'); // 关闭弹出框
    
                               $('#dg').datagrid('reload'); // reload the user data
    
                               $.messager.alert("操作", "操作成功!");
    
                           } else {
    
                               $.messager.alert("操作", "操作失败!");
    
                               return;
    
                           }
    
                       }
    
                   });
    
               }
    
     
    
               function removeUser() {
    
                   var row = $('#dg').datagrid('getSelections');
    
                   if (!row || row.length == 0) {
    
                       $.messager.alert('提示', '请选择要删除的数据');
    
                       return;
    
                   }
    
                   var parm;
    
                   $.each(row, function (i, n) {
    
                       if (i == 0) {
    
                           parm = n.Id;
    
                       }
    
                       else {
    
                           parm += "," + n.Id;
    
                       }
    
                   });
    
                   // alert(parm);
    
                   if (row) {
    
                       $.messager.confirm('删除信息', '您确定删除此条信息吗?', function (r) {
    
                           if (r) {
    
                               $.post('/Home/Delete/', { idList: parm }, function (result) {
    
                                   if (result.success) {
    
                                       $('#dg').datagrid('reload'); // reload the user data
    
                                       $.messager.alert("提示", "删除成功!");
    
                                   } else {
    
                                       $.messager.alert('提示', '删除失败,请检查!');
    
                                       return;
    
                                   }
    
                               }, 'json');
    
                           }
    
                       });
    
                   }
    
               }
    
        </script>
    
    </head>
    
    <body>
    
        <div>
    
            <table id="dg" title="人员管理" class="easyui-datagrid" fit="True" url="/Home/LoadAllByPage/" 
    
                             toolbar="#toolbar" pagination="true" rownumbers="true" fitColumns="true" sortName= "DepID" >
    
                          <thead>
    
                                 <tr>
    
                            <th checkbox="true" field="Cid"/>
    
                            <th field="Id" sortable="true" width="50">ID</th>
    
                                        <th field="DepID" sortable="true" width="50">部门ID</th>
    
                                        <th field="DepName" sortable="true" width="50">部门名称</th>
    
                                 </tr>
    
                          </thead>
    
               </table>
    
            <div id="toolbar">
    
                <input type="text" name="SSID" id="SSID" />
    
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-search" plain="true" onclick="check()">查询</a>
    
                      <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">增加</a>
    
                      <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">修改</a>
    
                      <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="removeUser()">删除</a>
    
               </div>
    
            <!--弹出框的显示!-->
    
               <div id="dlg" class="easyui-dialog" style="400px;height:300px;padding:10px 20px"
    
                             closed="true" buttons="#dlg-buttons">
    
                      <div class="ftitle">部门管理</div>
    
                      <form id="fm" method="post" novalidate>
    
                             <div class="fitem">
    
                    <input type="hidden" id="Id" name="Id"  />
    
                                    <label>部门ID</label>
    
                                    <input id="DepID" name="DepID" class="easyui-validatebox" required="true"  />
    
                             </div>
    
                             <div class="fitem">
    
                                    <label>部门名称</label>
    
                                    <input id="DepName" name="DepName" class="easyui-validatebox" required="true" />
    
                             </div>
    
                      </form>
    
               </div>
    
               <div id="dlg-buttons">
    
                      <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">确定</a>
    
                      <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">关闭</a>
    
               </div>
    
        </div>
    
    </body>
    
    复制代码
    
     
    
    这里我们这个项目就已经完成了,从这个项目中我们就可以知道后面其他的表是怎么操作的,所谓举一反三就是这个意思了!而且从这个项目中我们学习到了这么多的知识点,不过个人感觉思路清晰,什么都可以解决,记得我刚开始的时候,天天在整这些东西,每天都昏昏成成的,查资料的话资料还是非常的少,只能自己慢慢理解在慢慢捉摸了。所谓“功夫不负有心人”,OK,写了两个多小时了,完工吧,给自己留个纪念。
    
        第十二步:效果展示
    
    (1) 条件查询
    
     
    
    (1)    增加
    
     
    
    (3) 修改
    
     
  • 相关阅读:
    常见的分布式协议与算法【转】
    Linux的文件系统及文件缓存知识点整理【转】
    linux内核启动内核解压过程分析【转】
    Linux内核分析:Linux内核启动流程分析【转】
    Linux内核Ramdisk(initrd)机制【转】
    基于tiny4412的Linux内核移植 -- 设备树的展开【转】
    linux中RamDisk的三种实现方式【转】
    (十四)Linux kernel mmc 框架说明,包括mmc_test使用方法【转】
    ApplicationContext的初始化与销毁&Bean的生命周期&BeanPostProcessor的使用&Aware使用(四)
    Spring技术与内幕IoC实现(二)
  • 原文地址:https://www.cnblogs.com/gs21Joan/p/3921973.html
Copyright © 2011-2022 走看看