1. 程式人生 > >ibatis_struts_spring(SSI)框架配置

ibatis_struts_spring(SSI)框架配置

步驟一:建立 WEB  PROJECT 開啟 MyEclipse, File—>new—> Project,選擇 web Project,點 Next下一步,輸入工程名,點 Finish 完成。 步驟二:新增 Struts 支援 選擇web工程名,MyEclipse—>Capabilities—>Add Struts Capabilities,保持預設,點 Finish 完成。 PS: ActionForm是一個JavaBean,需繼承org.apache.struts.action.ActionForm類,它捕獲通過HTTP請求傳送的引數。ActionForm針對每個HTML表單中的欄位具有一個對應的屬性。ActionServlet匹配請求中的引數和ActionForm中的屬性,並呼叫ActionForm中的setter方法,將引數傳入ActionForm。 Action是一個Java類,需繼承org.apache.struts.action.Action類。ActionServlet將會組裝ActionForm,並將它傳遞給Action。 Action 通常負責:      輸入校驗      呼叫業務邏輯類執行業務邏輯操作      決定返回哪個ActionForward web.xml 的配置: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">   <servlet>              <servlet-name>action</servlet-name>              <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>              <init-param>                    <param-name>config</param-name>                    <param-value>/WEB-INF/struts-config.xml</param-value>              </init-param>              <init-param>                    <param-name>debug</param-name>                    <param-value>3</param-value>              </init-param>              <init-param>                    <param-name>detail</param-name>                    <param-value>3</param-value>              </init-param>              <load-on-startup>2</load-on-startup>        </servlet>        <servlet-mapping>              <servlet-name>action</servlet-name>              <url-pattern>*.do</url-pattern>        </servlet-mapping>        <welcome-file-list>              <welcome-file>index.jsp</welcome-file>        </welcome-file-list>    </web-app>    struts-config.xml配置檔案: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC        "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"        "http://struts.apache.org/dtds/struts-config_1_2.dtd"> <struts-config>     <data-sources /> <!-- 用於配置所需要的資料來源-->     <form-beans />   <!-- 用於配置多個ActionForm-->     <global-exceptions /><!-- 用於配置異常處理-->     <global-forwards />  <!-- 用於宣告全域性轉發-->     <action-mappings /> <!-- 用於配置多個Action--> </struts-config>   <!-- 注意標籤順序--> <form-beans>標籤內部可以包含多個<form-bean>標籤 <form-bean>標籤必須指定name和type屬性          name屬性是給此ActionForm一個標識名稱         type屬性指定了此ActionForm是哪個類,必須是全路徑的類名 <action>標籤可以配置的重要屬性包括:     path - 從頁面上通過一個什麼樣的URL路徑來訪問Action(不包含.do)          type – 訪問這個URL的時候,呼叫哪個Action類,這是Action的全路徑類名          name– 這個屬性用來標識哪個ActionForm將被建立,並將提交的表單元件給它          scope – FormBean的作用域範圍,可以取值為session和request,一般取值都是request 注意細節:所有的頁面請求由容器接收  Struts的核心元件是ActionServlet,像其它所有Servlet一樣,它是生存在容器中的,比如Tomcat、WebLogic等,當容器啟動的時候,它會讀取web.xml檔案(部署描述符),告訴容器它會裝入哪些Servlet 。 一個標準的Servlet是通過servlet-mapping來設定,哪些請求,將會被提交到哪些servlet中。 Struts的servlet-mapping配置一般是:  <servlet-mapping>     <servlet-name>action</servlet-name>     <url-pattern>*.do</url-pattern>  </servlet-mapping> 這樣配置的意思是:任何以.do結尾的URL請求,都會被髮送到ActionServlet進行處理。 步驟三:新增 Spring 支援 選擇 Web 工程,MyEclipse—> Capabilities—>Add Spring Capabilities,勾上 Spring 2.0 Web Libraries 來支援 web 專案,勾選上 Spring2.0 core Libraries。如果使用 AOP 技術則勾上 spring 2.0 AOP Libraries。點 Next,選擇預設,點選 Finish 按鈕,完成 Spring 支援的新增。 PS: Spring最常用的特性 利用Spring來建立物件(JavaBean工廠) 利用Spring構建業務邏輯層     管理依賴關係     適應需求變更 利用Spring建立資料訪問物件(DAO) 利用Spring進行事務處理    ApplicationContext的三種常用實現: (1)ClassPathXmlApplicationContext ; (2)FileSystemXmlApplicationContext ; (3)XmlWebApplicationContext ; 如:ApplicationContext context=new ClassPathXmlApplicationContext(“xxx.xml”); 可以通過ApplicationContext獲得BeanFactory:      BeanFactory factory=(BeanFactory)context.getBean("Bean的ID"); 步驟四:配置資料庫連線池—applicationContext.xml <?xml version="1.0" encoding="UTF-8"?>    <beans xmlns="http://www.springframework.org/schema/beans"           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xmlns:p="http://www.springframework.org/schema/p"       xsi:schemaLocation="                http://www.springframework.org/schema/beans                 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd         <!--  配置資料來源 -->     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >         <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>         <property name="username" value="scott" />         <property name="password" value="tiger" />         <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />     </bean> </beans> 配置資料來源時,會出現找不到org.apache.comons.dbcp.BasicDataSource 的 提示。需要引入資料庫連線池的jar 包:commons-dbcp.jar和commons-pool.jar。 步驟五:struts+spring 整合 在 struts 的配置檔案 struts-config.xml 中以外掛的方式整合spring,同時配置全域性的委託代理(可選)。 注意:plug-in 外掛必須寫在配置檔案的最後一項。 struts-config.xml配置檔案: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC        "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"        "http://struts.apache.org/dtds/struts-config_1_2.dtd">   <struts-config>   <data-sources />   <form-beans >   </form-beans>   <global-exceptions />   <global-forwards />   <action-mappings >   </action-mappings>     <!-- 整合Spring -->   <!-- 全域性委託代理 -->   <controller>         <set-property value="org.springframework.web.struts.DelegatingRequestProcessor" property="processorClass"/>   </controller>   <!-- 注入spring外掛 -->   <plug-in     className="org.springframework.web.struts.ContextLoaderPlugIn">         <set-property property="contextConfigLocation"     value="/WEB-INF/applicationContext.xml"/>   </plug-in> </struts-config>

步驟六:在Spring中配置事務管理—applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans     xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:p="http://www.springframework.org/schema/p"     xsi:schemaLocation="           http://www.springframework.org/schema/beans            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">     <!-- 配置資料來源  -->      <bean id="dataSource"              class="org.apache.commons.dbcp.BasicDataSource"              destroy-method="close">         <!--JDBC驅動-->              <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />            <!--資料庫URL-->             <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />             <!--資料庫使用者名稱-->            <property name="username" value="scott" />             <!--資料庫密碼-->            <property name="password" value="tiger" />          </bean>          <!-- 事務管理器 -->     <bean id="transactionManager"              class="org.springframework.jdbc.datasource.DataSourceTransactionManager">              <property name="dataSource" ref="dataSource" />          </bean>        <!-- 事務代理基類 -->     <bean id="txProxyTemplate" abstract="true" lazy-init="true"         class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">         <property name="transactionManager" ref="transactionManager"></property>         <property name="transactionAttributes">             <props>                 <prop key="do*">PROPAGATION_REQUIRED,-Exception</prop>             </props>         </property>     </bean>    </beans>

事務特性: PROPAGATION_REQUIRED: 在當前的事務中進行,如果沒有就建立一個新的事務 PROPAGATION_REQUIRES_NEW: 建立一個新的事務,如果現存一個事務就暫停它 PROPAGATION_MANDATORY: 方法必須在一個現存的事務中進行,否則丟出異常 PROPAGATION_NESTED: 在一個嵌入的事務中進行,如果不是,則同PROPAGATION_REQUIRED PROPAGATION_NEVER: 指出不應在事務中進行,如果有就丟出異常 PROPAGATION_NOT_SUPPORTED: 指出不應在事務中進行,如果有就暫停現存的事務 PROPAGATION_SUPPORTS: 支援現在的事務,如果沒有就以非事務的方式執行 事務應用:   <bean id="EmpService" parent="txProxyTemplate">    <property name="target">       <bean class="com.test.EmpServiceImpl">            <property name="empDao" ref="EmpDao"></property>        </bean>    </property> </bean> 注意: 不應該呼叫一個數據源的 getConnection()方法和Connection的close()方法,而必須使用Spring的 org.springframework.jdbc.datasource.DataSourceUtils類 如下: Connection conn = DataSourceUtils.getConnection(dataSource);      … DataSourceUtils.releaseConnection(conn, dataSource); 步驟七:Spring 整合 Ibatis 匯入 iBatis相關JAR包:ibatis-2.3.4.726.jar   配置檔案:Jdbc連線的屬性檔案(jdbc.properties) driverClassName=oracle.jdbc.driver.OracleDriver   url=jdbc:oracle:thin:@localhost:1521:orcl     username=scott      password=tiger     配置檔案:Spring配置檔案(applicationContext.xml) <?xml version="1.0" encoding="UTF-8"?> <beans     xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:p="http://www.springframework.org/schema/p"     xsi:schemaLocation="           http://www.springframework.org/schema/beans            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">     <bean id="propertyConfigurer"            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">         <property name="locations">             <list>                 <value>/WEB-INF/jdbc.properties</value>             </list>                    </property>            </bean>     <!-- 配置資料來源  -->      <bean id="dataSource"              class="org.apache.commons.dbcp.BasicDataSource"              destroy-method="close">         <!--JDBC驅動-->              <property name="driverClassName" value="${driverClassName}" />            <!--資料庫URL-->             <property name="url" value="${url}" />             <!--資料庫使用者名稱-->            <property name="username" value="${username}" />             <!--資料庫密碼-->            <property name="password" value="${password}" />          </bean>          <!-- 事務管理器 -->     <bean id="transactionManager"              class="org.springframework.jdbc.datasource.DataSourceTransactionManager">              <property name="dataSource" ref="dataSource" />          </bean>        <!-- 事務代理基類 -->     <bean id="txProxyTemplate" abstract="true"         class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">         <property name="transactionManager" ref="transactionManager"></property>         <property name="transactionAttributes">             <props>                 <prop key="do*">PROPAGATION_REQUIRED,-Exception</prop>             </props>         </property>     </bean>        <!-- 根據資料訪問資源,例項化SqlMapClient物件 -->     <bean id="baseSqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">         <property name="configLocation" value="/WEB-INF/SqlMapConfig.xml"></property>         <property name="dataSource" ref="dataSource"></property>     </bean>     <!-- 建立sqlMapClientTemplate -->     <bean id="baseSqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate">         <constructor-arg>             <ref bean="baseSqlMapClient" />         </constructor-arg>     </bean>     <!-- 例項化EmpDao,注入sqlMapClientTemplate物件 -->     <bean id="EmpDao" class="com.test.EmpDaoImpl">         <property name="sqlMapClientTemplate" ref="baseSqlMapClientTemplate"></property>     </bean>     <!-- 例項化EmpService,注入empDao物件 -->     <bean id="EmpService" parent="txProxyTemplate">          <property name="target">               <bean class="com.test.EmpServiceImpl">                     <property name="empDao" ref="EmpDao"></property>               </bean>          </property>     </bean>     <!-- 例項化emp,注入empService物件 -->     <bean name="/emp" class="com.test.EmpAction">         <property name="empService" ref="EmpService"></property>     </bean> </beans> 配置檔案:iBaits總配置檔案(SqlMapConfig.xml) <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMapConfig   PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"          "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">          <!-- Ibatis配置檔案-->          <sqlMapConfig>                 <!--   cacheModelsEnabled:是否啟動SqlMapClient的快取機制。          enhancementEnabled:是否針對POJO啟用位元組碼增加機制以提升geter/seter的呼叫效用,        為延遲載入帶來了及大的效能提升。           lazyLoadingEnabled:是否啟用延遲載入機制。           maxRequests:最大並大請求數。           maxSessions:最大Session數,即當前最大允許的開發SqlMapClient數           maxTransactions:最大併發事務數。      -->           <settings               cacheModelsEnabled="true"              enhancementEnabled="true"              lazyLoadingEnabled="true"              maxRequests="32"              maxSessions="10"              maxTransactions="5"              useStatementNamespaces="true"          />        <!--載入SqlMap檔案-->           <sqlMap resource="emp.xml" />      </sqlMapConfig>     配置檔案:關於每個實體的對映檔案(SQL Mapping檔案emp.xml) <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"       "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <sqlMap namespace="EMP">       <typeAlias alias="emp" type="com.test.EmpBean" />       <select id="getEmp" resultClass="emp">         SELECT * FROM emp       </select>   </sqlMap> 實現EmpDaoImpl類 :          繼承SqlMapClientDaoSupport類並實現DAO介面。          呼叫SqlMapClientTemplate類提供的方法進行資料操作。 public class EmpDaoImpl extends SqlMapClientDaoSupport implements IEmpDao    {       @SuppressWarnings("unchecked")       public List getEmp()       {           List resultList = new ArrayList();           try         {               resultList= (List)getSqlMapClientTemplate().queryForList("EMP.getEmp", null);           }           catch(Exception e)           {               System.out.println("查詢錯誤!");           }           return resultList;       }          } iBatis的實現原理:         iBatis使用簡單的XML描述檔案,將Java Bean、Map和基本資料型別對映成JDBC的PreparedStatement的輸入引數和ResultSet結果集,實現Sql語句的動態拼接,及ResultSet結果集到Java物件的自動轉換。