SSH整合(Struts+Spring+Hibernate)
環境:
struts2.3.X
spring4.0.0
hibernate4.2
思路:從下開始往上整合;層與層之間沒有關係;在整合的時候,只關注當前整合的那個層的內容;
1,建立一個空的web專案;重新定位class檔案編譯路徑
2,設定專案的編碼;
3,完成domain;
4,完成對映檔案;
5,寫DAO介面;
6,寫DAO實現
1),拷包(hiberante/required,資料庫驅動,springcore/test/bean/context);
2),spring配置檔案:
1),配置datasource;
2),新增db.properties檔案;
3),引入db.properties檔案;
3),配置sessionFactory
1),匯入spring jdbc/tx/orm;
2),使用LocalSessionFactoryBean來建立SessionFactory;
1),配置dataSource;
2),配置hibernate的其他相關配置:直接在classpath下面建立一個hibernate.proeprties檔案,在這裡面加上show_sql,dailect,hbm2ddl.auto等hibernate配置;(spring會自動的載入和讀入);
3),配置對映檔案:使用的是掃描hbm.xml檔案所在的資料夾路徑來引入的(mappingDirectoryLocations,這個配置後面的內容可以使用classpath:字首,注意是檔案路徑)
4),完成DAO:
1),直接在dao中注入一個SessionFactory;
2),在DAO中直接使用SessionFactory.getCurrentSession()來得到我們需要的session;
3),千萬不要開啟事務;
4),千萬不要手賤關session;
5),在spring中配置DAO;
1),抽象一個baseDAO;<bean id="baseDAO" abstract="true" />
2),讓employeeDAO繼承BaseDAO;<bean id="employeeDAO" parent="baseDAO" />
7,寫Service:
1),完成service介面和實現;
2),在spring中配置servicebean;
3),配置事務:
1),配置transcationMaanager,使用HibernateTransactionManager,並傳入一個sessionFactory;
2),配置事務屬性;
3),配置事務切面;
8,整合Struts2
1),拷貝相關內容(struts2.xml,struts2的jar包,web.xml)
2),完成Action;
3),在Spring中配置Action;注意,action的scope需要是prototype的;
4),完成struts的配置檔案:
注意,在action的class屬性,不能再寫Action的類限定名;只能寫這個Action在spring中配置的bean的id值;
5),匯入spring-web.jar,struts2-spring-plugin.jar;
6),在web.xml中新增<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
7),在web.xml中新增spring框架啟動的載入的配置檔案路徑:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
struts整合spring原理
在struts2-spring-plugin.jar中:
<!--配置了一個名字叫做spring的StrutsSpringObjectFactory -->
<bean type="com.opensymphony.xwork2.ObjectFactory" name="spring" class="org.apache.struts2.spring.StrutsSpringObjectFactory" />
<!-- struts.objectFactory代表,在struts中,使用哪個類來作為工廠類,生產struts需要的bean(包括action,interceptor) -->
<constant name="struts.objectFactory" value="spring" />