接着昨天的繼續吧,我們的完美征程繼續開始。昨天我們完成了MVC里面的Dao層的設計,在上面我們已經實現了操作數據庫的代碼,在這個項目中我實現了User_DepInfo表的增刪改查和模糊查詢,是基於EasyUI寫的。
- 第六步:實現Server的接口: NewKJ241.IBLL
(1) 這個接口的作用和NewKJ241.IDao類庫里面類的接口一模一樣,目的是為了分層更加的明確,而且在后面還有一個類要繼承自這個接口,在類庫NewKJ241.IBLL下面新建一個類名,起名為:IUserDepInfoBLL,代碼因為和上面那個接口的代碼一模一樣的,所以我就不寫出來了。
- 第七步:繼承Server接口:NewKJ241.BLL
(1) 這個類的作用是繼承自IUserDepInfoBLL類,實現的是調用前面Dao里面的接口,實現Dao的方法,這樣分層會非常的明確,在NewKJ241.BLL類庫下面新建一個UserDepInfoBLL,在類里面調用Dao接口的方法實現所有的方法,代碼如下:
public class UserDepInfoBLL<T>:IUserDepInfoBLL<T> where T:class { private IUserDepInfoDao<T> userDepInfoDao; public IUserDepInfoDao<T> UserDepInfoDao { get { return userDepInfoDao; } set { userDepInfoDao = value; } } public T Get(object id) { if (id == null) { return null; } else { return this.UserDepInfoDao.Get(id); } } public T Load(object id) { if (id == null) { return null; } else { return this.UserDepInfoDao.Load(id); } } public object Save(T entity) { if (entity == null) { return null; } else { return this.UserDepInfoDao.Save(entity); } } public void Update(T entity) { if (entity == null) { return; } else { this.UserDepInfoDao.Update(entity); } } public void SaveOrUpdate(T entity) { if (entity == null) { return; } else { this.UserDepInfoDao.SaveOrUpdate(entity); } } public void Delete(object id) { if (id == null) { return; } else { this.UserDepInfoDao.Delete(id); } } public void Delete(string idList) { if (idList == null && idList.Split(',').Length == 0) { return; } else { this.UserDepInfoDao.Delete(idList); } } public IList<UserDepInfo> loadByAll(string sort, string order) { return this.UserDepInfoDao.loadByAll(sort, order); } public IList<UserDepInfo> loadAllCheck(string sort, string order, string name) { return this.UserDepInfoDao.loadAllCheck(sort, order, name); } public IList<UserDepInfo> LoadAllByPage(out long total, int page, int rows, string order, string sort, string DepName) { return this.UserDepInfoDao.LoadAllByPage(out total, page, rows, order, sort, DepName); } }
- 第八步: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<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<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; width: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="width: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) 修改
下載地址:http://www.chuxinm.com/Shop/Detail/Detail?id=b88e9907dbaa4b3db297443081ab238d