net的web.config程序配置MVC3+Spring.net+nhibernate

一、打开vs2010,菜单文件->新建->项目->其它项目类型->vs解决方案

工程结构分部:

       Solution-

                     src

                          Domain

                                        Entities

                                        Mappings

                          Dao

                                        Config

                                        Interface

                                        InterfaceImpl

                          Nhibernate(这一层可以不写用上面的)

                                        Nhibernate

                          Service

                                        Interface

                                        InterfaceImpl                                       

                          Web工程

                     lib

                     doc

1、新建一个类库工程domain,位置路径为解决方案路径下面的src下面。

vs工程新建的时候必须看下工程的属性必须选择 .net framework 4 默认是client这个有问题。使用spring.net和nhibernate时候报引用错误

 

2、在Domain工程下新建2个文件夹Entities和Mappings,然后使用自动生成工具生成entities和mappings文件并添加进vs2010对应工程文件夹,因为用了动软生成实体,和codesmith生成配置文件所以生成的文件名字、字段属性可能不一致,这里需要修改一下(最好不要带下划线。属性名不要加表名作为前缀)。

 用到mapping的时候配置文件必须是嵌入式的否则会报错(这个在winform中是这样,但是如果把配置文件放到web项目方案下面可以不是,用context 在web.config中使用file调用未测试,下面只针对controller.xml 做了这样的修改,因为其他部分和winform的配置一样。)

Error creating context 'spring.root': InputStream is null from Resource = [assembly [Dao, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [Dao.Dao.Config.Dao.xml]]

3、再次新建类库工程Dao(Service)下面新建2个文件夹Dao、DaoImpl(Service、ServiceImpl)。添加对应的业务接口可实现。

4、添加web工程Web添加Config文件夹,编写Controller.xml 配置文件

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">

  <object type="Web.Controllers.HomeController, Web" singleton="false" >
    <property name="Message" value="Welcome to ASP.NET MVC3 powered by Spring.NET!" />
    <property name="RalasafeRoleService" ref="RalasafeRoleService"/>
  </object>
</objects>

Web工程下必须修改下Global.asax文件

 public class MvcApplication :  SpringMvcApplication 必须继承这个SpringMvcApplication 

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            // 日志启动 
            log4net.Config.XmlConfigurator.Configure();
        }

不然spring不会加载controller的配置文件里面的属性。

<property name="Message" value="Welcome to ASP.NET MVC3 powered by Spring.NET!" />
    <property name="RalasafeRoleService" ref="RalasafeRoleService"/>

添加controller action文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Collections;
using System.Text;
using Web.Tools;
using Service.Interface;
using Domain.Entities;

namespace Web.Controllers
{
    public class HomeController : AbstractController
    {
        #region Fields
        public string Message { get; set; }
        private IRalasafeRoleService ralasafeRoleService;

        #endregion

        #region Properties

        public IRalasafeRoleService RalasafeRoleService
        {
            get { return ralasafeRoleService; }
            set { ralasafeRoleService = value; }
        }

        #endregion

        public ActionResult Index()
        {
            //simple asp.net mvc sample app hard-coded message commented out b/c we
            // can property-inject it via the container instead
            // (gratuitous container usage trick, but demonstrates that the container
            //  is resolving HomeController)
            
            //ViewData["Message"] = "Welcome to ASP.NET MVC!";

            //set the message value in the viewdata bag based on the property value
            // as injected into the controller from the container
            ViewData["Message"] = Message;

            return View();
        }
         public ActionResult Login()
        {
            return View("Login");
        }
        
         public JsonResult getAccordionMenu()
        {
            IList<RalasafeRole> list = RalasafeRoleService.GetRalasafeRoles();
            Hashtable rtnVal = new Hashtable();
            List<Object> items = new List<Object>();
            Object item1 = new
            {
                ID = 1,
                ProductCode = "1KDB",
            };
            items.Add(item1);
            Object item2 = new
            {
                ID = 2,
                ProductCode = "S5GRA",
            };
            items.Add(item2);
            rtnVal["items"] = items;
            return CreateJsonNetResult(true, rtnVal);
        }
     
    }
}
前台写个js程序测试下

Ext.Ajax.request({
        url: 'Home/getAccordionMenu',
        params: {
            iMenuParentId: 0
        },
        method: 'post',
        callback: function (options, success, response) {
            //调用回调函数  
            		    	alert(response);//
            		    	alert(response.responseText);
            var json = Ext.decode(response.responseText);
            var obj = Ext.decode(json).childrenItem;
            addTree(obj);
            //                addTree(Ext.JSON.decode(response.responseText));  //将后台传送json字符串 转为对象
        },
        failure: function (response, opts) {
            alert(response.responseText);
            console.log('server-side failure with status code ' + response.status);
        }
    });

二、配置web.config

1、在Web工程中添加web.config xml配置文件

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->

<configuration>

  <configSections>
    <!--Spring 配置节点id-->
    <sectionGroup name="spring">
      <!--这里的context属性和winform程序不一样,因为是mvc3web程序所以改为MvcContextHandler-->
      <section name="context" type="Spring.Context.Support.MvcContextHandler, Spring.Web.Mvc3"/>
      <section name="parsers" type="Spring.Context.Support.NamespaceParsersSectionHandler, Spring.Core"/>
      <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
    </sectionGroup>
    <!--Log4net 日志配置节点id-->
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
    <!--配置文件中定义了关于数据访问的一些配置参数,以备以后使用-->
    <section name="databaseSettings" type="System.Configuration.NameValueSectionHandler"/>
  </configSections>
  <spring>
    <context>
      <!--第一种 表示在app.config配置文件的<spring><objects>配置节内部定义了<object />托管对象。例如下面的 -->
      <resource uri="config://spring/objects"/>
      <!--第二种最常用 读取嵌入在程序集中的配置文件 assembly://MyAssembly/MyProject+package/xml  -->
      <!--Dao-->
      <resource uri="assembly://Dao/Dao.Config/Dao.xml"/>
      <!--Service-->
      <resource uri="assembly://Service/Service.Config/Service.xml"/>
      <!--Web-->
      <!--第二种第三种从web 的Context中获取这里的配置xml属性不要写成嵌入式的改成context的  -->
      <resource uri="file://~/Config/Controller.xml"/>
      <!--<resource uri="assembly://Web/Web.Config/Controller.xml"/>-->
    </context>
    <parsers>
      <parser type="Spring.Data.Config.DatabaseNamespaceParser, Spring.Data"/>
      <parser type="Spring.Transaction.Config.TxNamespaceParser, Spring.Data"/>
    </parsers>
    <!--第一种就是把Dao.xml的托管对象内容贴到这里App.config 在Context配置节中作如下指示-->
    <objects xmlns="http://www.springframework.net">
      <description>An  example that demonstrates simple IoC features.</description>
      <!--<object id="Form1" type="WinForm.Form1">-->
      <!--</object>-->
    </objects>

  </spring>

  <!-- These properties are referenced in Dao.xml -->
  <!--配置文件中定义了关于数据访问的一些配置参数,以备以后使用-->
  <databaseSettings>
    <add key="db.datasource" value="127.0.0.1"/>
    <add key="db.user" value="root"/>
    <add key="db.password" value=""/>
    <add key="db.database" value="ralasafe"/>
  </databaseSettings>

  <!--log4net 配置节点id对应具体的配置文件位置-->
  <log4net>
    <!--控制台输出日志-->
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%-5level %logger - %message%newline"/>
      </layout>
    </appender>
    <!--文件日志输出-->
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender,log4net">
      <param name="File" value="Logs/Log.log" />
      <param name="AppendToFile" value="true" />
      <param name="MaxSizeRollBackups" value="10" />
      <param name="MaximumFileSize" value="10MB" />
      <param name="RollingStyle" value="Size" />
      <param name="StaticLogFileName" value="true" />
      <param name="datePattern" value="yyyy-MM-dd HH:mm" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
      </layout>
    </appender>

    <!--默认日志输出级别根节点,其它没有写的话都继承这个Set default logging level to DEBUG-->
    <root>
      <level value="DEBUG"/>
      <appender-ref ref="ConsoleAppender"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </root>

    <!--设置其他插件日志输出Set logging for Spring.  Logger names in Spring correspond to the namespace-->
    <logger name="Spring">
      <level value="DUBUG"/>
    </logger>

    <logger name="Spring.Data">
      <level value="DUBUG"/>
    </logger>

    <logger name="NHibernate">
      <level value="DUBUG"/>
    </logger>


  </log4net>
  <appSettings>
    <!-- 在appsettings中一定要加这句话,用于注册NHibernate的SessionFactory-->
    <add key="Spring.Data.NHibernate.Support.OpenSessionInViewModule.SessionFactoryObjectName" value="NHibernateSessionFactory"/>
    <!--<add key="ClientValidationEnabled" value="true"/>--> 
    <!--<add key="UnobtrusiveJavaScriptEnabled" value="true"/>--> 
  </appSettings>
    
  <system.web>
    <!--用于注册spring.net和nhibernate-->
    <!-- Spring 提供的 Module  -->
    <httpModules>
      <add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"/>
      <!-- 
          由 Spring 自动打开会话,必须提供一个名为 SessionFactory 的会话工厂 
          使用后,可以使用 SessionFactory 的 GetCurrentSession 方法获取会话
      -->
      <add name="OpenSessionInView" type="Spring.Data.NHibernate.Support.OpenSessionInViewModule, Spring.Data.NHibernate32"/>
    </httpModules>
    <httpHandlers>
      <!-- Spring 提供的处理程序 -->
      <add verb="*" path="*.aspx" type="Spring.Web.Support.PageHandlerFactory, Spring.Web"/>
      <!-- 取消 Spring.NET 对于 Web 服务的处理 -->
      <add verb="*" path="*.asmx" type="Spring.Web.Services.WebServiceHandlerFactory, Spring.Web"/>
      <add verb="*" path="ContextMonitor.ashx" type="Spring.Web.Support.ContextMonitor, Spring.Web"/>
    </httpHandlers>
    
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>

    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>

    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages"/>
      </namespaces>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>


2、Dao.xml配置文件下面红色标注的地方必须注意不同版本可能有所区别,文档上的跟新不是很及时有些东西是老的容易出错。还是要看版本更新列表说明。

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net"
         xmlns:db="http://www.springframework.net/database">

  <!-- Referenced by main application context configuration file -->
  <description>
    The Northwind object definitions for the Data Access Objects.
  </description>
  <!-- 用来读取Web.config中设置的databaseSettings 可以给下面的db:provider引用-->
  <object type="Spring.Objects.Factory.Config.PropertyPlaceholderConfigurer, Spring.Core">
    <property name="ConfigSections" value="databaseSettings"/>
  </object>

  <!-- Database Configuration -->
  <db:provider id="DbProvider"
               provider="MySql-5.2.3"
  connectionString="Data Source=${db.datasource};Database=${db.database};User Id=${db.user};Password=${db.password};"/>
  <!--connectionString="Data Source=127.0.0.1;Database=kasai;User Id=root;Password="/>-->

  <!-- NHibernate Configuration -->
  <object id="NHibernateSessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate32">
    <property name="DbProvider" ref="DbProvider"/>
    <property name="MappingAssemblies">
      <list>
        <!--mapping所在程序集-->
        <value>Domain</value>
      </list>
    </property>
    <property name="HibernateProperties">
      <dictionary>
        <!--配置属性不同版本key和value可能都不一样文档上的跟新不是很及时有些东西是老的容易出错。还是要看版本更新列表说明-->
        <entry key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
        <entry key="dialect" value="NHibernate.Dialect.MySQL5Dialect"/>
        <entry key="connection.driver_class" value="NHibernate.Driver.MySqlDataDriver"/>
        <entry key="use_proxy_validator" value="false" />
      </dictionary>
    </property>

    <!-- provides integation with Spring's declarative transaction management features  -->
    <!--允许您使用Spring的声明式事务  区别于编程式事务不需要在代码中写事务commit-->
    <property name="ExposeTransactionAwareSessionFactory" value="true" />

  </object>


  <!-- Transaction Management Strategy - local database transactions -->
  <!-- 配置事务管理策略,本地数据库事务 -->
  <object id="transactionManager"
        type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate32">

    <property name="DbProvider" ref="DbProvider"/>
    <property name="SessionFactory" ref="NHibernateSessionFactory"/>

  </object>


  <!-- Exception translation object post processor-->
  <object type="Spring.Dao.Attributes.PersistenceExceptionTranslationPostProcessor, Spring.Data"/>

  <!-- Data Access Objects -->
  <object id="RalasafeRoleDao" type="Dao.InterfaceImpl.RalasafeRoleDao, Dao">
    <property name="SessionFactory" ref="NHibernateSessionFactory"/>
  </object>

</objects>

2.3 Servcie.xml 配置

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net"
         xmlns:tx="http://www.springframework.net/tx">

  <!-- Referenced by main application context configuration file -->

  <description>
    The  service layer definitions
  </description>

  <!-- Property placeholder configurer for database settings -->
  <object id="RalasafeRoleService" type="Service.InterfaceImpl.RalasafeRoleService, Service">
    <property name="RalasafeRoleDao" ref="RalasafeRoleDao"/>
  </object>

  <!--支持事务的特性,可以在代码中使用注解写事务-->
  <tx:attribute-driven/>
</objects>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值