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

   SSH框架之Spring+Struts2+Hibernate整合篇    
回顧 -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"><action name="customerAction_*" class="customerAction" method="{1}">/jsp/customer/add.jsp
        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 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 findAllCustomer() {                return customerDao.findAllCustomer();
            }

            @Override            public void saveCustomer(Customer customer) {
                customerDao.saveCustomer(customer);
            }
        }        1.2.5第六步:建立持久層接口        /**
         * 客戶的持久層接口         */
        public interface ICustomerDao {            
            /**
             * 查詢全部客戶
             * @return
             */
            List 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配置文件並導入約束        <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">
        2.1.3第三步:把業務層和持久層配置到文件中        
        <bean id="customerDao" class="com.baidu.dao.impl.CustomerDaoImpl"><bean id="customerService" class="com.baidu.service.impl.CustomerServiceImpl">
            

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

            @Override            public List 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第二步:編寫實體類的映射文件        
        <!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"><generator class="native">class>2.2.3第三步:編寫hibernate主配置文件        
        <!DOCTYPE hibernate-configuration PUBLIC            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
            "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">com.mysql.jdbc.Driverjdbc:mysql:///crmroperty>
                root1234
                org.hibernate.dialect.MySQLDialecttruefalseupdateorg.hibernate.connection.C3P0ConnectionProviderthread2.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        <bean id="sessionFactory" 
                    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        2.3.2.2第二步:改造Dao繼承HibernateDaoSupport        /**
         * 客戶的持久層實現類         */
        public class CustomerDaoImpl extends HibernateDaoSupport implements ICustomerDao {

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

            @Override            public void saveCustomer(Customer customer) {
                getHibernateTemplate().save(customer);
            }
        }        2.3.2.3第三步:在spring配置文件中給Dao注入SessionFactory        <bean id="customerDao" class="com.baidu.dao.impl.CustomerDaoImpl">2.3.2.4第四步:測試        /**
         * 整合spring和hibernate的測試類
         * spring整合Junit
         *     第一步:拷貝jar包
         *         spring-junit-4.2.4.jar
         *  第二步:使用註解替換運行器(原來junit的main方法)
         *      @RunWith(支持spring的main方法)
         *      @ContextConfiguration(指定spring的配置文件位置)         */
        @RunWith(SpringJUnit4Cla***unner.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綁定到當前線程上的配置 
        thread-->
        
            org.springframework.orm.hibernate5.SpringSessionContext        

        此時再運行剛纔的測試:
                查詢可使用了。保存不能使用,緣由是沒有事務。        2.3.3配置Spring的事務        2.3.3.1第一步:配置事務管理器並注入SessionFactory        <bean id="transactionManager" 
                class="org.springframework.orm.hibernate5.HibernateTransactionManager">
            2.3.3.2第二步:配置事務的通知及通知的屬性        2.3.3.3第三步:配置AOP創建切入點表達式和事務通知的關係        

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

        2.4.5第五步:修改menu.jsp        
            - 新增客戶        
        2.4.6第六步:在struts.xml中配置action
        /jsp/customer/add.jsp2.4.7第七步:編寫動做類和方法
        /**
         * 客戶的動做類        */
        public class CustomerAction extends ActionSupport implements ModelDriven {            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-class>
                org.springframework.web.context.ContextLoaderListener            class>

        當配置了此監聽器後,就不須要使用Action的構造函數了,能夠把構造函數那段刪除了。
        此監聽器只能讀取WEB-INF目錄中的名稱爲applicationContext.xml的配置文件。這顯然限制了咱們的配置。
        咱們能夠經過配置全局初始化參數的方式,指定spring配置文件的位置.        2.6.2配置指定spring配置文件的位置
        咱們把spring配置文件放到此處,須要配置全局初始化參數:        contextConfigLocationclasspath:config/spring/applicationContext.xml2.6.3分文件編寫spring配置
        咱們寫到這裏,其實搭建環境已經基本結束了,可是發現spring的配置文件雜亂無章,使咱們在找配置的時候,很難一下找到。因此咱們採用分配置文件編寫的方式。        2.6.3.1編寫主配置文件引入其餘配置文件        <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">
            
            <import resource="applicationContext-customer.xml"/>
            <import resource="applicationContext-jdbc.xml"/>
            <import resource="applicationContext-tx.xml"/>2.6.3.2編寫針對需求的配置文件applicationContext-customer.xml        <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="customerDao" class="com.baidu.dao.impl.CustomerDaoImpl"><bean id="customerService" 
                            class="com.baidu.service.impl.CustomerServiceImpl">
                2.6.3.3編寫數據庫鏈接的配置文件applicationContext-jdbc.xml        <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="sessionFactory" 
                    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
            <property name="configLocation"value="classpath:config/hibernate/hibernate.cfg.xml">/>2.6.3.4編寫事務控制的配置文件applicationContext-tx.xml        <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">
                <aop:pointcut expression="execution(* com.baidu.service.impl.*.*(..))"id="pt1"/>
                2.6.4配置指定struts2配置文件位置
        咱們的spring和hibernate配置文件都存到了src/config/的對應包中了,只有struts2配置文件還在類的根路徑下,它也能夠經過配置的方式指定struts.xml的位置。配置的是過濾器的初始化參數。初始化參數的name和value都是固定寫法。        struts2<filter-class>
                org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter            class>config
                    struts-default.xml,struts-plugin.xml,config/struts/struts.xml                struts2/*2.6.5分文件編寫struts2配置文件
        當咱們後面作的模塊愈來愈多,struts2一個配置文件寫起來也會雜亂無章,因此咱們也能夠把struts2的配置文件分開編寫。
        2.6.5.1編寫struts2的主配置文件struts.xml
        
        2.6.5.2針對不一樣模塊編寫不一樣的配置文件struts-customer.xml
        
        /jsp/customer/add.jsp/jsp/customer/list.jsp2.6.6管理Action的兩種方式
        2.6.6.1第一種方式:讓struts2本身來管理
        此種方式就是在action標籤的class屬性中提供動做類的全限定類名。/jsp/customer/add.jsp2.6.6.2第二種方式:讓spring來管理(實際開發中採用的方式)
        此種方式就是在spring配置文件中配置Action,在struts2配置文件action標籤的class屬性裏寫bean的id。

        spring配置文件:
        struts2配置文件:
        /jsp/customer/add.jsp第3章基於XML的引入式整合
        3.1明確
        引入式整合就是把hibernate.cfg.xml中的配置都挪到spring的配置文件中
        3.2配置方式
        org.hibernate.dialect.MySQLDialecttruefalseupdateorg.springframework.orm.hibernate5.SpringSessionContext。
                    mappingLocations:配置映射文件的位置,須要寫映射文件名稱。可使用通配符。
                    mappingDirectoryLocations:配置映射文件的位置,直接寫到包的目錄便可。
                -->classpath:com/baidu/domain/*.hbm.xml第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名稱空間及約束
        4.2.1.3第三步:在spring配置文件中配置要掃描的包
        4.2.1.4第四步:把action,service和dao都用註解配置
        /**
         * 客戶的動做類         */
        @Controller("customerAction")
        @Scope("prototype")        public class CustomerAction extends ActionSupport implements ModelDriven {
            @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;            //dao中的方法不變        }        4.2.1.5第五步:在spring配置文件中配置HiernateTemplate        <bean id="hibernateTemplate" 
                class="org.springframework.orm.hibernate5.HibernateTemplate">
            4.2.1.6第六步:在spring配置文件中配置事務管理器        <bean id="transactionManager" 
                class="org.springframework.orm.hibernate5.HibernateTransactionManager">
            4.2.1.7第七步:在spring配置文件中開啓spring對註解事務的支持        4.2.1.8第八步:在客戶的業務層實現類上使用@Transactional註解        /**
         * 客戶的業務層實現類         */
        @Service("customerService")
        @Transactional(readOnly=false,propagation=Propagation.REQUIRED)        public class CustomerServiceImpl implements ICustomerService {
            
            @Autowired            private ICustomerDao customerDao;

            @Override
            @Transactional(readOnly=true,propagation=Propagation.SUPPORTS)            public List findAllCustomer() {                return customerDao.findAllCustomer();
            }

            @Override            public void saveCustomer(Customer customer) {
                customerDao.saveCustomer(customer);
            }
        }        4.2.2hibernate映射使用註解配置實現        4.2.2.1實體類映射註解配置        /**
         * 客戶的實體類
         *  JPA規範:java 持久化規範
         *  註解全都是JPA規範的。
         *  導包都須要導入javax.persistence包下的
         *         */
        @Entity
        @Table(name="cst_customer")        public class Customer implements Serializable {
            
            @Id
            @GeneratedValue(strategy=GenerationType.IDENTITY)
            @Column(name="cust_id")            private Long custId;
            @Column(name="cust_name")            private String custName;
            @Column(name="cust_source")            private String custSource;
            @Column(name="cust_industry")            private String custIndustry;
            @Column(name="cust_level")            private String custLevel;
            @Column(name="cust_address")            private String custAddress;
            @Column(name="cust_phone")            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 + "]";
            }    
        }        4.2.2.2spring中SessionFactory配置修改        <bean id="sessionFactory" 
                class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
            
                        org.hibernate.dialect.MySQLDialect                    truefalseupdate
                        org.springframework.orm.hibernate5.SpringSessionContext                    com.baidu.domain4.2.3struts2配置使用註解實現        4.2.3.1導入struts2註解的jar包        4.2.3.2使用註解配置Action        /**
         * 客戶的動做類         */
        @Controller("customerAction")
        @Scope("prototype")        //-------如下都是struts2的註解-----------
        @ParentPackage("struts-default")//指定當前包的父包
        @Namespace("/customer")//指定名稱空間,訪問當前action的全部方法都須要有名稱空間
        public class CustomerAction extends ActionSupport implements ModelDriven {            private Customer customer = new Customer();
            
            @Autowired            private ICustomerService customerService;    
            
            @Override            public Customer getModel() {                return customer;
            }            
            /**
             * 查詢全部客戶
             * @return
             */
            private List customers;            //用於配置動做名稱
            @Action(value="findAllCustomer",results={
                    @Result(name="findAllCustomer",
                            type="dispatcher",
                            location="/jsp/customer/list.jsp")
            })            public String findAllCustomer(){
                customers = customerService.findAllCustomer();                return "findAllCustomer";
            }            
            /**
             * 獲取添加客戶頁面
             * @return
             */
            @Action(value="addUICustomer",results={
                    @Result(name="addUICustomer",
                            location="/jsp/customer/add.jsp")
            })            public String addUICustomer(){                return "addUICustomer";
            }            
            /**
             * 添加客戶
             * @return
             */
            @Action(value="addCustomer",results={
                    @Result(name="addCustomer",
                            type="redirect",
                            location="/jsp/success.jsp")
            })            public String addCustomer(){
                customerService.saveCustomer(customer);                return "addCustomer";
            }            
            public List getCustomers() {                return customers;
            }            public void setCustomers(List customers) {                this.customers = customers;
            }
Spring整合Struts2的底層實現原理,由Spring來建立action對象 (原理在包struts2-spring-plugin-2.3.24.jar中)        package com.baidu.customer.action;        import com.baidu.customer.domain.Customer;        import com.baidu.customer.service.CustomerService;        import com.opensymphony.xwork2.ActionSupport;        import com.opensymphony.xwork2.ModelDriven;        /**
         * 客戶模塊
         * @author Administrator         */
        public class CustomerAction extends ActionSupport implements ModelDriven{            
            private Customer customer = new Customer();            public Customer getModel() {                return customer;
            }            
            /**
             * 跳轉到新增頁面
             * @return
             * @throws Exception             */
            public String initSave() throws Exception {                return "initSave";
            }
            這種方式是ation對象由struts2建立的            // 對象工廠,經過name自動裝配對象  customerService(底層經過jar包用常量覆蓋struts2的默認配置,開啓spring的對象工廠,當瀏覽器訪問的時候            ,訪問到action之後再建立CustomerService對象時,用名稱name在SpringIOC容器裏面找,找到之後返回到Action的set方法的CustomerService裏面,給CustomerService賦一個實現類對象值)            private CustomerService customerService;            public void setCustomerService(CustomerService customerService) {                this.customerService = customerService;
            }            public String save() throws Exception {
                System.out.println("WEB層:保存客戶...");
                customerService.save(customer);                return NONE;
            }

        }
相關文章
相關標籤/搜索