SSH框架之Spring+Struts2+Hibernate整合篇

来源:https://www.cnblogs.com/haizai/archive/2019/09/22/11568801.html
-Advertisement-
Play Games

回顧 -Hibernate框架 ORM: 對象關係映射.把資料庫表和JavaBean通過映射的配置文件映射起來, 操作JavaBean對象,通過映射的配置文件生成SQL語句,自動執行.操作資料庫. 1: 類名.hbm.xml 映射配置文件. 2: hibernate.cfg.xml 核心配置文件. ... ...


回顧 -Hibernate框架
        ORM: 對象關係映射.把資料庫表和JavaBean通過映射的配置文件映射起來,
        操作JavaBean對象,通過映射的配置文件生成SQL語句,自動執行.操作資料庫. 
    1: 類名.hbm.xml 映射配置文件.
    2: hibernate.cfg.xml 核心配置文件.
    3: 使用Hibernate提供的API操作.

    Struts2框架 : 和客戶端進行交互
    1. 在web.xml配置過濾器.
    2. struts.xml配置文件.
    
    Spring框架
    1. applicationContext.xml配置
    2. 核心IOC和AOP
    3. 事務管理.
    CustomerAction類    在struts.xml配置中配置的
    1. Action對象由Struts2框架創建的.
        CustomerAction:創建CustomerAction對象,由Struts2框架創建的    --->    Spring的IOC容器中對象,找customerService對象,預設按名稱找的.
        
    2. Action對象也可以由Spring框架類創建
        <bean id="customerAction" class="com.baidu.customer.action.CustomerAction" scope="prototype">
            <property name="customerService" ref="customerService"/>
        </bean>
        
        <action name="customerAction_*" class="customerAction" method="{1}">
            <result name="initSave">/jsp/customer/add.jsp</result>
        </action>
        
day67_Spring_05
            第1章整合前的準備
        1.1整合說明
        a.獨立式整合指的是三個框架都使用自己的配置文件。
        b.引入式整合指的是hibernate主配置文件中的內容都配置到spring配置文件中
        c.在整合過程中,確保每步都運行成功,然後在繼續往下做。
        d.整合中使用的案例是客戶的保存和列表查詢操作。
        e.後面的三種整合方式都基於1.2中的環境準備。
        1.2環境準備
        1.2.1第一步:創建java web工程
        此處使用Servlet2.5規範。
        1.2.2第二步:創建資料庫和表結構
        create database crm;
        use crm;

        /*創建客戶表*/
        CREATE TABLE `cst_customer` (
          `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客戶編號(主鍵)',
          `cust_name` varchar(32) NOT NULL COMMENT '客戶名稱(公司名稱)',
          `cust_source` varchar(32) DEFAULT NULL COMMENT '客戶信息來源',
          `cust_industry` varchar(32) DEFAULT NULL COMMENT '客戶所屬行業',
          `cust_level` varchar(32) DEFAULT NULL COMMENT '客戶級別',
          `cust_address` varchar(128) DEFAULT NULL COMMENT '客戶聯繫地址',
          `cust_phone` varchar(64) DEFAULT NULL COMMENT '客戶聯繫電話',
          PRIMARY KEY (`cust_id`)
        ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
        1.2.3第三步:編寫實體類
        /**
         * 客戶的實體類(數據模型)
         */
        public class Customer implements Serializable {

            private Long custId;
            private String custName;
            private String custSource;
            private String custIndustry;
            private String custLevel;
            private String custAddress;
            private String custPhone;
            public Long getCustId() {
                return custId;
            }
            public void setCustId(Long custId) {
                this.custId = custId;
            }
            public String getCustName() {
                return custName;
            }
            public void setCustName(String custName) {
                this.custName = custName;
            }
            public String getCustSource() {
                return custSource;
            }
            public void setCustSource(String custSource) {
                this.custSource = custSource;
            }
            public String getCustIndustry() {
                return custIndustry;
            }
            public void setCustIndustry(String custIndustry) {
                this.custIndustry = custIndustry;
            }
            public String getCustLevel() {
                return custLevel;
            }
            public void setCustLevel(String custLevel) {
                this.custLevel = custLevel;
            }
            public String getCustAddress() {
                return custAddress;
            }
            public void setCustAddress(String custAddress) {
                this.custAddress = custAddress;
            }
            public String getCustPhone() {
                return custPhone;
            }
            public void setCustPhone(String custPhone) {
                this.custPhone = custPhone;
            }
            @Override
            public String toString() {
                return "Customer [custId=" + custId + ", custName=" + custName + ", custSource=" + custSource
                        + ", custIndustry=" + custIndustry + ", custLevel=" + custLevel + ", custAddress=" + custAddress
                        + ", custPhone=" + custPhone + "]";
            }    
        }
        1.2.4第四步:編寫業務層介面和實現類
        /**
         * 客戶的業務層介面
         */
        public interface ICustomerService {

            /**
             * 查詢所有客戶
             * @return
             */
            List<Customer> findAllCustomer();
            
            /**
             * @param customer
             */
            void saveCustomer(Customer customer);
        }

        /**
         * 客戶的業務層實現類
         */
        public class CustomerServiceImpl implements ICustomerService {

            private ICustomerDao customerDao;

            public void setCustomerDao(ICustomerDao customerDao) {
                this.customerDao = customerDao;
            }

            @Override
            public List<Customer> findAllCustomer() {
                return customerDao.findAllCustomer();
            }

            @Override
            public void saveCustomer(Customer customer) {
                customerDao.saveCustomer(customer);
            }
        }
        1.2.5第六步:創建持久層介面
        /**
         * 客戶的持久層介面
         */
        public interface ICustomerDao {
            
            /**
             * 查詢所有客戶
             * @return
             */
            List<Customer> findAllCustomer();
            
            /**
             * 保存客戶
             * @param customer
             */
            void saveCustomer(Customer customer);
        }

        註意:做上述操作時,並不需要導入任何jar包。
        第2章基於XML的獨立式整合
        2.1保證spring框架在web工程中獨立運行
        2.1.1第一步:拷貝spring的ioc,aop和事務控制三組jar包

        2.1.2第二步:編寫spring配置文件並導入約束
        <?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:aop="http://www.springframework.org/schema/aop"
                xmlns:tx="http://www.springframework.org/schema/tx" 
                xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx.xsd
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop.xsd">
        </beans>
        2.1.3第三步:把業務層和持久層配置到文件中
        <!-- 把資源交給spring來管理 -->
        <!-- 配置dao -->
        <bean id="customerDao" class="com.baidu.dao.impl.CustomerDaoImpl"></bean>
            
        <!-- 配置service -->
        <bean id="customerService" class="com.baidu.service.impl.CustomerServiceImpl">
            <!-- 註入dao -->
            <property name="customerDao" ref="customerDao"></property>
        </bean>

        持久層實現類代碼:
            此時不要做任何操作,就輸出一句話。目的是測試spring框架搭建的結果。
        /**
         * 客戶的持久層實現類
         */
        public class CustomerDaoImpl implements ICustomerDao {

            @Override
            public List<Customer> findAllCustomer() {    
                System.out.println("查詢了所有用戶");
                return null;
            }

            @Override
            public void saveCustomer(Customer customer) {
                System.out.println("保存了用戶");
            }

        }
        2.1.4第四步:測試spring能否獨立運行
        /**
         * 測試類,測試spring框架可以獨立運行
         */
        public class Spring01Test {

            public static void main(String[] args) {
                //1.獲取spring容器
                ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
                //2.跟Id獲取bean對象
                ICustomerService customerService = (ICustomerService) ac.getBean("customerService");
                customerService.findAllCustomer();
            }
        }

        2.2保證hibernate框架能夠在web工程中獨立運行
        2.2.1第一步:拷貝hibernate必備jar包到工程的lib目錄
         
        2.2.2第二步:編寫實體類的映射文件
        <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE hibernate-mapping PUBLIC 
            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
            "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
        <hibernate-mapping package="com.baidu.domain">
            <class name="Customer" table="cst_customer">
                <id name="custId" column="cust_id">
                    <generator class="native"></generator>
                </id>
                <property name="custName" column="cust_name"></property>
                <property name="custSource" column="cust_source"></property>
                <property name="custIndustry" column="cust_industry"></property>
                <property name="custLevel" column="cust_level"></property>
                <property name="custAddress" column="cust_address"></property>
                <property name="custPhone" column="cust_phone"></property>
            </class>
        </hibernate-mapping>

        2.2.3第三步:編寫hibernate主配置文件
        <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE hibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
            "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
        <hibernate-configuration>
            <session-factory>
                <!-- 1.連接資料庫的信息 -->
                <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
                <property name="hibernate.connection.url">jdbc:mysql:///crmroperty>
                <property name="hibernate.connection.username">root</property>
                <property name="hibernate.connection.password">1234</property>
                <!-- 2.hibernate的基本配置 -->
                <!-- 資料庫的方言-->
                <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
                <!-- 是否顯示sql語句-->
                <property name="hibernate.show_sql">true</property>
                <!-- 是否格式化sql語句-->
                <property name="hibernate.format_sql">false</property>
                <!-- 採用何種方式生成資料庫表結構 -->
                <property name="hibernate.hbm2ddl.auto">update</property>
                <!-- 配置使用c3p0數據源 -->
                <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
                <!--把session綁定到當前線程上的配置-->
                <property name="hibernate.current_session_context_class">thread</property>
                <!-- 3.映射文件的位置 -->
                <mapping resource="com/baidu/domain/Customer.hbm.xml"/>
            </session-factory>
        </hibernate-configuration>
        2.2.4第四步:編寫測試類-測試保存客戶
        /**
         * hibernate的測試類
         *         保證hibernate框架可以獨立運行
         */
        public class Hibernate02Test {

            @Test
            public void testFindAll(){
                //1.讀取配置文件
                Configuration cfg = new Configuration();
                cfg.configure();
                //2.根據配置文件獲取SessionFactory
                SessionFactory factory = cfg.buildSessionFactory();
                //3.根據SessionFactory獲取一個Session
                Session s = factory.getCurrentSession();
                //4.開啟事務
                Transaction tx = s.beginTransaction();
                //5.執行操作
                Query query = s.createQuery("from Customer");
                List list = query.list();
                for(Object o : list){
                    System.out.println(o);
                }
                //6.提交事務
                tx.commit();
                //7.釋放資源
                factory.close();
            }
            
            @Test
            public void testSave(){
                Customer c = new Customer();
                c.setCustName("傳智專修學院");
                //1.讀取配置文件
                Configuration cfg = new Configuration();
                cfg.configure();
                //2.根據配置文件獲取SessionFactory
                SessionFactory factory = cfg.buildSessionFactory();
                //3.根據SessionFactory獲取一個Session
                Session s = factory.getCurrentSession();
                //4.開啟事務
                Transaction tx = s.beginTransaction();
                //5.執行操作
                s.save(c);
                //6.提交事務
                tx.commit();
                //7.釋放資源
                factory.close();
            }
        }
        2.3整合spring和hibernate框架
        2.3.1明確
        a.Spring和Hibernate的整合就是spring接管SessionFactory的創建
        b.Spring針對Hiberante的操作有一個封裝的對象HibernateTemplate
        c.和JdbcTemplate一樣,HibernateTemplate也有一個HibernateDaoSupport
        d.HibernateTemplate和HibernateDaoSupport都在spring-orm-4.2.4.RELEASE.jar中
        e.我們Dao採用繼承HiberanteDaoSupport的方式編寫,它一樣不能用於註解配置。
        2.3.2整合步驟
        2.3.2.1第一步:在spring配置文件中配置SessionFactory
        <!-- 配置SessionFactory -->
        <bean id="sessionFactory" 
                    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 使用的是hibernate主配置文件中的內容,我們只需要指定hibernate主配置文件的所在位置 -->
            <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
        </bean>
        2.3.2.2第二步:改造Dao繼承HibernateDaoSupport
        /**
         * 客戶的持久層實現類
         */
        public class CustomerDaoImpl extends HibernateDaoSupport implements ICustomerDao {

            @Override
            public List<Customer> findAllCustomer() {    
                return (List<Customer>) getHibernateTemplate().find("from Customer");
            }

            @Override
            public void saveCustomer(Customer customer) {
                getHibernateTemplate().save(customer);
            }
        }
        2.3.2.3第三步:在spring配置文件中給Dao註入SessionFactory
        <!-- 配置dao -->
        <bean id="customerDao" class="com.baidu.dao.impl.CustomerDaoImpl">
            <property name="sessionFactory" ref="sessionFactory"></property>
        </bean>
        2.3.2.4第四步:測試
        /**
         * 整合spring和hibernate的測試類
         * spring整合Junit
         *     第一步:拷貝jar包
         *         spring-junit-4.2.4.jar
         *  第二步:使用註解替換運行器(原來junit的main方法)
         *      @RunWith(支持spring的main方法)
         *      @ContextConfiguration(指定spring的配置文件位置)
         */
        @RunWith(SpringJUnit4ClassRunner.class)
        @ContextConfiguration(locations={"classpath:bean.xml"})
        public class SpringHibernate03Test {
            
            @Autowired
            private ICustomerService customerService;

            @Test
            public void testFindAll(){
                List list = customerService.findAllCustomer();
                for(Object o : list){
                    System.out.println(o);
                }
            }
            
            @Test
            public void testSave(){
                Customer c = new Customer();
                c.setCustName("傳智學院test");        
                customerService.saveCustomer(c);
            }
        }
        測試結果:
            無論保存還是查詢都運行失敗!
            按常理來說,我們沒有配置事務,保存失敗是可以理解的。為什麼查詢也會失敗呢?
        分析原因:
            是由於spring的HibernateTemplate對象在使用Session時,spring創建了Session的代理對象,在這個過程中,spring對hibernate綁定Session到當前線程的配置不認識了,所以運行失敗。
        2.3.2.5第五步:修改把Session綁定到當前線程上
        <!-- 是hibernate把session綁定到當前線程上的配置 
        <property name="hibernate.current_session_context_class">thread</property>-->
        <!-- 是spring把sesion綁定到當前線程上的配置 -->
        <property name="hibernate.current_session_context_class">
            org.springframework.orm.hibernate5.SpringSessionContext
        </property>

        此時再運行剛纔的測試:
                查詢可以使用了。保存不能使用,原因是沒有事務。
        2.3.3配置Spring的事務
        2.3.3.1第一步:配置事務管理器並註入SessionFactory
        <!-- 配置事務管理器 -->
        <bean id="transactionManager" 
                class="org.springframework.orm.hibernate5.HibernateTransactionManager">
            <!-- 註入SessionFactory -->
            <property name="sessionFactory" ref="sessionFactory"></property>
        </bean>
        2.3.3.2第二步:配置事務的通知及通知的屬性
        <!-- 配置事務的通知 -->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <!-- 配置事務的屬性 -->
            <tx:attributes>
                <tx:method name="*" read-only="false" propagation="REQUIRED"/>
                <tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
            </tx:attributes>
        </tx:advice>
        2.3.3.3第三步:配置AOP建立切入點表達式和事務通知的關係
        <!-- 配置aop -->
        <aop:config>
            <!-- 配置通用切入點表達式 -->
            <aop:pointcut expression="execution(* com.baidu.service.impl.*.*(..))" id="pt1"/>
            <!-- 建立事務通知和切入點表達式的對應關係 -->
            <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
        </aop:config>

        再次測試:
            此時保存和查詢都可以正常使用了。
        2.4保證struts2框架能夠在web工程中獨立運行
        2.4.1第一步:拷貝struts2的必備jar包
        要把畫紅線的jar包刪掉,因為hibernate中有個高版本的。
        2.4.2第二步:在類的類的根路徑下編寫struts.xml文件並導入約束
        <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE struts PUBLIC
            "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
            "http://struts.apache.org/dtds/struts-2.3.dtd">
        <struts>
            <!-- 開啟開發者模式 -->
            <constant name="struts.devMode" value="true"></constant>
        </struts>
        2.4.3第三步:在web.xml中配置struts2的核心過濾器
        <filter>
            <filter-name>struts2</filter-name>
            <filter-class>
                org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
            </filter-class>
        </filter>
        <filter-mapping>
            <filter-name>struts2</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        2.4.4第四步:導入jsp頁面

        2.4.5第五步:修改menu.jsp
        <A class=style2 
            href="${pageContext.request.contextPath}/customer/addUICustomer.action"  
            target=main>
            - 新增客戶
        </A>
        2.4.6第六步:在struts.xml中配置action
        <!--  獲取添加客戶頁面 -->
        <action name="addUICustomer" class="com.baidu.web.action.CustomerAction" 
                    method="addUICustomer">
            <result name="addUICustomer">/jsp/customer/add.jsp</result>
        </action>
        2.4.7第七步:編寫動作類和方法
        /**
         * 客戶的動作類
        */
        public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {
            private Customer customer = new Customer();

            @Override
            public Customer getModel() {
                return customer;
            }
            
            /**
             * 獲取添加客戶頁面
             * @return
             */
            public String addUICustomer(){
                return "addUICustomer";
            }
        }
        2.4.8第八步:測試
        運行結果:通過點擊【新增客戶】可以跳轉到客戶添加頁面
        2.5整合spring和struts2
        2.5.1明確
        a.spring整合struts2就是讓spring接管action的創建
        b.action是多例的,配置到spring中需要設置scope屬性為多例
        2.5.2整合步驟
        2.5.2.1第一步:拷貝struts2-spring-plugin-2.3.24.jar到lib目錄

        2.5.2.2第二步:在action中使用構造函數獲取Service對象
        public CustomerAction(){
            ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(
                                    ServletActionContext.getServletContext());
                //由於動作類是多例的,每次都會創建容器,導致資源的浪費。一個應用應該只有一個容器
                System.out.println(ac);
                customerService = (ICustomerService) ac.getBean("customerService");
            }
        2.5.2.3第三步:測試
        運行結果:查詢客戶列表測試通過。保存測試通過。
        2.6優化配置
        2.6.1配置spring的監聽器
        在上面2.5.2.2小節中有這麼一句:
            由於動作類是多例的,每次都會創建容器,導致資源的浪費。一個應用應該只有一個容器
        問題:
            如何解決呢?
        答案:
            只要讓容器在應用載入時創建,應用卸載時銷毀就可以。
        問題:
            我們怎麼知道應用何時載入了呢?
        答案:
            ServletContext對象創建了,就表示當前應用已經被伺服器載入了。
        問題:
            我們怎麼知道ServletContext對象創建了呢?
        答案:
            ServletContextListener監聽器可以監聽到ServletContext對象的創建和銷毀。

        Spring框架為我們提供了一個監聽器:ContextLoaderListener。
        它是ServletContextListener介面的實現類,負責監聽ServletContext對象的創建,為我們創建容器,監聽ServletContext對象的銷毀,銷毀容器。
        我們只需要配置上即可。
        ContextLoaderListener在spring-web-4.2.4.RELEASE.jar中
        所以我們要先導入這個jar包。
        ,在web.xml中配置監聽器:
        <listener>
            <listener-class>
                org.springframework.web.context.ContextLoaderListener
            </listener-class>
        </listener>

        當配置了此監聽器後,就不需要使用Action的構造函數了,可以把構造函數那段刪除了。
        此監聽器只能讀取WEB-INF目錄中的名稱為applicationContext.xml的配置文件。這顯然限制了我們的配置。
        我們可以通過配置全局初始化參數的方式,指定spring配置文件的位置.
        2.6.2配置指定spring配置文件的位置
        我們把spring配置文件放到此處,需要配置全局初始化參數:
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/spring/applicationContext.xml</param-value>
        </context-param>
        2.6.3分文件編寫spring配置
        我們寫到這裡,其實搭建環境已經基本結束了,但是發現spring的配置文件雜亂無章,使我們在找配置的時候,很難一下找到。所以我們採用分配置文件編寫的方式。
        2.6.3.1編寫主配置文件引入其他配置文件
        <?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:aop="http://www.springframework.org/schema/aop"
                xmlns:tx="http://www.springframework.org/schema/tx" 
                xsi:schemaLocation="http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/tx 
                    http://www.springframework.org/schema/tx/spring-tx.xsd
                    http://www.springframework.org/schema/aop 
                    http://www.springframework.org/schema/aop/spring-aop.xsd">
            <!-- 引入其他spring配置文件 -->
            <import resource="applicationContext-customer.xml"/>
            <import resource="applicationContext-jdbc.xml"/>
            <import resource="applicationContext-tx.xml"/>
        </beans>
        2.6.3.2編寫針對需求的配置文件applicationContext-customer.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:aop="http://www.springframework.org/schema/aop"
                xmlns:tx="http://www.springframework.org/schema/tx" 
                xsi:schemaLocation="http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/tx 
                    http://www.springframework.org/schema/tx/spring-tx.xsd
                    http://www.springframework.org/schema/aop 
                    http://www.springframework.org/schema/aop/spring-aop.xsd">
            <!-- 把資源交給spring來管理 -->
            <!-- 配置dao -->
            <bean id="customerDao" class="com.baidu.dao.impl.CustomerDaoImpl">
                <property name="sessionFactory" ref="sessionFactory"></property>
            </bean>
            
            <!-- 配置service -->
            <bean id="customerService" 
                            class="com.baidu.service.impl.CustomerServiceImpl">
                <!-- 註入dao -->
                <property name="customerDao" ref="customerDao"></property>
            </bean>
        </beans>
        2.6.3.3編寫資料庫連接的配置文件applicationContext-jdbc.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:aop="http://www.springframework.org/schema/aop"
                xmlns:tx="http://www.springframework.org/schema/tx" 
                xsi:schemaLocation="http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/tx 
                    http://www.springframework.org/schema/tx/spring-tx.xsd
                    http://www.springframework.org/schema/aop 
                    http://www.springframework.org/schema/aop/spring-aop.xsd">
            
            <!-- 配置SessionFactory -->
            <bean id="sessionFactory" 
                    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
            <!-- 使用的是hibernate主配置文件中的內容,我們只需要指定hibernate配置文件的位置 -->
                <property name="configLocation" 
                           value="classpath:config/hibernate/hibernate.cfg.xml">/>
            </bean>
        </beans>
        2.6.3.4編寫事務控制的配置文件applicationContext-tx.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:aop="http://www.springframework.org/schema/aop"
                xmlns:tx="http://www.springframework.org/schema/tx" 
                xsi:schemaLocation="http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/tx 
                    http://www.springframework.org/schema/tx/spring-tx.xsd
                    http://www.springframework.org/schema/aop 
                    http://www.springframework.org/schema/aop/spring-aop.xsd">

            
            <!-- 配置事務管理器 -->
            <bean id="transactionManager" 
                class="org.springframework.orm.hibernate5.HibernateTransactionManager">
                <!-- 註入SessionFactory -->
                <property name="sessionFactory" ref="sessionFactory"></property>
            </bean>
            
            <!-- 配置事務的通知 -->
            <tx:advice id="txAdvice" transaction-manager="transactionManager">
                <!-- 配置事務的屬性 -->
                <tx:attributes>
                    <tx:method name="*" read-only="false" propagation="REQUIRED"/>
                    <tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
                </tx:attributes>
            </tx:advice>
            
            <!-- 配置aop -->
            <aop:config>
                <!-- 配置通用切入點表達式 -->
                <aop:pointcut expression="execution(* com.baidu.service.impl.*.*(..))" 
                                id="pt1"/>
                <!-- 建立事務通知和切入點表達式的對應關係 -->
                <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
            </aop:config>
        </beans>
        2.6.4配置指定struts2配置文件位置
        我們的spring和hibernate配置文件都存到了src/config/的對應包中了,只有struts2配置文件還在類的根路徑下,它也可以通過配置的方式指定struts.xml的位置。配置的是過濾器的初始化參數。初始化參數的name和value都是固定寫法。

        <filter>
            <filter-name>struts2</filter-name>
            <filter-class>
                org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
            </filter-class>
            <init-param>
                <param-name>config</param-name>
                <param-value>
                    struts-default.xml,struts-plugin.xml,config/struts/struts.xml
                </param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>struts2</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        2.6.5分文件編寫struts2配置文件
        當我們後面做的模塊越來越多,struts2一個配置文件寫起來也會雜亂無章,所以我們也可以把struts2的配置文件分開編寫。
        2.6.5.1編寫struts2的主配置文件struts.xml
        <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE struts PUBLIC
            "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
            "http://struts.apache.org/dtds/struts-2.3.dtd">
        <struts>
            <!-- 開啟開發者模式 -->
            <constant name="struts.devMode" value="true"></constant>
            
            <package name="myDefault" extends="struts-default" abstract="true">
                <!--  有公共的配置就寫在此處,沒有就空著 -->
            </package>

            <!--引入其他struts2配置文件 -->
            <include file="config/struts/struts-customer.xml"></include>
        </struts>
        2.6.5.2針對不同模塊編寫不同的配置文件struts-customer.xml
        <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE struts PUBLIC
            "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
            "http://struts.apache.org/dtds/struts-2.3.dtd">
        <struts>
            <package name="customer" extends="myDefault" namespace="/customer">
                <!--  獲取添加客戶頁面 -->
                <action name="addUICustomer" 
                        class="com.baidu.web.action.customerAction" 
                        method="addUICustomer">
                    <result name="addUICustomer">/jsp/customer/add.jsp</result>
                </action>
                
                <!--  查詢客戶列表 -->
                <action name="findAllCustomer" 
                        class=" com.baidu.web.action.customerAction" 
                        method="findAllCustomer">
                    <result name="findAllCustomer">/jsp/customer/list.jsp</result>
                </action>
            </package>
        </struts>
        2.6.6管理Action的兩種方式
        2.6.6.1第一種方式:讓struts2自己來管理
        此種方式就是在action標簽的class屬性中提供動作類的全限定類名。

        <action name="addUICustomer" 
                class="com.baidu.web.action.customerAction" 
                method="addUICustomer">
            <result name="addUICustomer">/jsp/customer/add.jsp</result>
        </action>
        2.6.6.2第二種方式:讓spring來管理(實際開發中採用的方式)
        此種方式就是在spring配置文件中配置Action,在struts2配置文件action標簽的class屬性里寫bean的id。

        spring配置文件:
        <!-- 配置Action -->
        <bean id="customerAction" class="com.baidu.web.action.CustomerAction" 
                scope="prototype">
            <!-- 註入service -->
            <property name="customerService" ref="customerService"></property>
        </bean>    

        struts2配置文件:
        <!--  獲取添加客戶頁面 -->
        <action name="addUICustomer" class="customerAction" method="addUICustomer">
            <result name="addUICustomer">/jsp/customer/add.jsp</result>
        </action>

        第3章基於XML的引入式整合
        3.1明確
        引入式整合就是把hibernate.cfg.xml中的配置都挪到spring的配置文件中
        3.2配置方式
        <!-- 配置SessionFactory -->
        <bean id="sessionFactory" 
                class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
                <!-- 1、連接資料庫的信息 -->
                <property name="dataSource" ref="dataSource"></property>
                <!-- 2、hibernate的基本配置 -->
                <property name="hibernateProperties">
                    <props>
                        <!-- 資料庫的方言-->
                        <prop key="hibernate.dialect">
                                org.hibernate.dialect.MySQLDialect
                        </prop>
                        <!-- 是否顯示sql語句-->
                        <prop key="hibernate.show_sql">true</prop>
                        <!-- 是否格式化sql語句-->
                        <prop key="hibernate.format_sql">false</prop>
                        <!-- 採用何種方式生成資料庫表結構 -->
                        <prop key="hibernate.hbm2ddl.auto">update</prop>
                        <!-- 是spring把sesion綁定到當前線程上的配置 -->
                        <prop key="hibernate.current_session_context_class">
                            org.springframework.orm.hibernate5.SpringSessionContext
                        </prop>
                    </props>
                </property>
                <!-- 3、映射文件的位置 
                    mappingResources:配置映射文件的位置,需要寫映射文件名稱。
                                      並且有幾個映射文件,就要寫幾個<value></value>。
                    mappingLocations:配置映射文件的位置,需要寫映射文件名稱。可以使用通配符。
                    mappingDirectoryLocations:配置映射文件的位置,直接寫到包的目錄即可。
                -->
                <property name="mappingLocations">
                    <array>
                        <value>classpath:com/baidu/domain/*.hbm.xml</value>
                    </array>
                </property>
            </bean>

        <!-- 配置數據源 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql:///crm"></property>
            <property name="user" value="root"></property>
            <property name="password" value="1234"></property>
        </bean>
        第4章基於註解的整合
        4.1明確
        a.註解整合仍然使用上面的環境,就是把xml的配置全部換成註解
        b.spring的註解整合有兩種方式,一種是用xml文件,一種是純註解。
        c.hibernate註解整合是把實體類映射改為JPA註解映射
        4.2整合步驟-spring使用xml文件
        4.2.1spring配置使用註解實現
        4.2.1.1第一步:導入spring的必備jar包
        之前的環境已經導入。略。
        4.2.1.2第二步:在spring配置文件中導入context名稱空間及約束
        <?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:aop="http://www.springframework.org/schema/aop"
                xmlns:tx="http://www.springframework.org/schema/tx" 
                xmlns:context="http://www.springframework.org/schema/context" 
                xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx.xsd
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop.xsd
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context.xsd">
        </beans>
        4.2.1.3第三步:在spring配置文件中配置要掃描的包
        <!-- 配置spring運行要掃描的包 -->
        <context:component-scan base-package="com.baidu"></context:component-scan>
        4.2.1.4第四步:把action,service和dao都用註解配置
        /**
         * 客戶的動作類
         */
        @Controller("customerAction")
        @Scope("prototype")
        public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {
            @Autowired
            private ICustomerService customerService;
            //action中的方法不變
        }

        /**
         * 客戶的業務層實現類
         */
        @Service("customerService")
        public class CustomerServiceImpl implements ICustomerService {
            @Autowired
            private ICustomerDao customerDao;
            //service中的方法不變
        }

        /**
         * 客戶的持久層實現類
         */
        @Repository("customerDao")
        public class CustomerDaoImpl implements ICustomerDao {
            //dao中必須自己定義HibernateTemplate,不能繼承HibernateDaoSupport了
            @Autowired
            private HibernateTemplate hibernateTemplate;
           

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 先上完成的效果圖:列是根據查詢結果增加的 數據格式: 表頭的數據取出: element table中: 表格內數據整理: 左側表頭合併:需要註意的是,當有固定列的時候需要設置表格的max-height屬性,不然會出現列空白 <el-table :data="tableData" span-metho ...
  • 一.vue基礎 "Vue的介紹及安裝和導入" "Vue的使用" "Vue成員獲取" "Vue中的迴圈以及修改差值表達式" "vue中methods,computed,filters,watch的總結" "Vue中組件" "Vue中插槽指令" "Vue部分編譯不生效,解決Vue渲染時候會閃一下" 二. ...
  • 1、絕對定位 絕對定位指的是通過規定HTML元素在水平和垂直方向上的位置來固定元素,基於絕對定位的元素不會占據空間。 絕對定位的位置聲明是相對於已定位的並且包含關係最近的祖先元素。如果當前需要被定為的元素沒有已定位的祖先元素作為參考值,則相對於整個網頁。 position:absolute; 1 < ...
  • 水平居中(包含塊中居中)1. 定寬,左右margin為auto。(常規流塊盒、彈性項目[不用定寬]) 例子:在box1盒子上設置寬,再設置margin:auto; 得到的效果: 2. 彈性盒設置justify-content: center,讓彈性項目在主軸上居中。(普遍適應) 例子:在其父元素上設 ...
  • 一、HTMLhtyper text markup language 即超文本標記語言超文本: 就是指頁面內可以包含圖片、鏈接,甚至音樂、程式等非文字元素。標記語言: 標記(標簽)構成的語言.網頁==HTML文檔,由瀏覽器解析,用來展示的靜態網頁:靜態的資源,如xxx.html 動態網頁:html代碼... ...
  • 垂死病中驚坐起,笑問 Bug 何處來?! 1、先是大寫字母作祟 前兩天發佈了「柒留言」v2.0.0 新版本,結果...你懂的嘛,沒有 Bug 的程式不是好程式,寫不出 Bug 的程式員不是好程式員。 那個,有一兩個小 Bug 很正常的啦。 有用戶反饋,收到了留言回覆的通知,但是點進去沒有內容。怎麼會 ...
  • meta標簽:description【對網站做簡單的描述,用戶是不可見】 <meta name="description" content="測試標簽、元素"/> meta標簽:keywords【關鍵詞,為了確保搜索引擎能正確的匹配到關鍵詞是要對準網頁主題,用戶不可見】 <meta name="ke ...
  • 一 Django的視圖函數view 一個視圖函數(類),簡稱視圖,是一個簡單的Python 函數(類),它接受Web請求並且返回Web響應。 響應可以是一張網頁的HTML內容,一個重定向,一個404錯誤,一個XML文檔,或者一張圖片。 無論視圖本身包含什麼邏輯,都要返迴響應。代碼寫在哪裡也無所謂,只 ...
一周排行
    -Advertisement-
    Play Games
  • 1. 說明 /* Performs operations on System.String instances that contain file or directory path information. These operations are performed in a cross-pla ...
  • 視頻地址:【WebApi+Vue3從0到1搭建《許可權管理系統》系列視頻:搭建JWT系統鑒權-嗶哩嗶哩】 https://b23.tv/R6cOcDO qq群:801913255 一、在appsettings.json中設置鑒權屬性 /*jwt鑒權*/ "JwtSetting": { "Issuer" ...
  • 引言 集成測試可在包含應用支持基礎結構(如資料庫、文件系統和網路)的級別上確保應用組件功能正常。 ASP.NET Core 通過將單元測試框架與測試 Web 主機和記憶體中測試伺服器結合使用來支持集成測試。 簡介 集成測試與單元測試相比,能夠在更廣泛的級別上評估應用的組件,確認多個組件一起工作以生成預 ...
  • 在.NET Emit編程中,我們探討了運算操作指令的重要性和應用。這些指令包括各種數學運算、位操作和比較操作,能夠在動態生成的代碼中實現對數據的處理和操作。通過這些指令,開發人員可以靈活地進行算術運算、邏輯運算和比較操作,從而實現各種複雜的演算法和邏輯......本篇之後,將進入第七部分:實戰項目 ...
  • 前言 多表頭表格是一個常見的業務需求,然而WPF中卻沒有預設實現這個功能,得益於WPF強大的控制項模板設計,我們可以通過修改控制項模板的方式自己實現它。 一、需求分析 下圖為一個典型的統計表格,統計1-12月的數據。 此時我們有一個需求,需要將月份按季度劃分,以便能夠直觀地看到季度統計數據,以下為該需求 ...
  • 如何將 ASP.NET Core MVC 項目的視圖分離到另一個項目 在當下這個年代 SPA 已是主流,人們早已忘記了 MVC 以及 Razor 的故事。但是在某些場景下 SSR 還是有意想不到效果。比如某些靜態頁面,比如追求首屏載入速度的時候。最近在項目中回歸傳統效果還是不錯。 有的時候我們希望將 ...
  • System.AggregateException: 發生一個或多個錯誤。 > Microsoft.WebTools.Shared.Exceptions.WebToolsException: 生成失敗。檢查輸出視窗瞭解更多詳細信息。 內部異常堆棧跟蹤的結尾 > (內部異常 #0) Microsoft ...
  • 引言 在上一章節我們實戰了在Asp.Net Core中的項目實戰,這一章節講解一下如何測試Asp.Net Core的中間件。 TestServer 還記得我們在集成測試中提供的TestServer嗎? TestServer 是由 Microsoft.AspNetCore.TestHost 包提供的。 ...
  • 在發現結果為真的WHEN子句時,CASE表達式的真假值判斷會終止,剩餘的WHEN子句會被忽略: CASE WHEN col_1 IN ('a', 'b') THEN '第一' WHEN col_1 IN ('a') THEN '第二' ELSE '其他' END 註意: 統一各分支返回的數據類型. ...
  • 在C#編程世界中,語法的精妙之處往往體現在那些看似微小卻極具影響力的符號與結構之中。其中,“_ =” 這一組合突然出現還真不知道什麼意思。本文將深入剖析“_ =” 的含義、工作原理及其在實際編程中的廣泛應用,揭示其作為C#語法奇兵的重要角色。 一、下劃線 _:神秘的棄元符號 下劃線 _ 在C#中並非 ...