美文网首页
SSH项目_01三大框架的整合

SSH项目_01三大框架的整合

作者: 编程_书恨少 | 来源:发表于2018-08-27 18:30 被阅读0次

    1. 单独整合spring到项目中

    1. 导包
      antlr-2.7.7.jar
      asm-3.3.jar
      asm-commons-3.3.jar
      asm-tree-3.3.jar
      com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar
      com.springsource.org.aopalliance-1.0.0.jar
      com.springsource.org.apache.commons.logging-1.1.1.jar
      com.springsource.org.apache.log4j-1.2.15.jar
      com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
      commons-fileupload-1.3.1.jar
      commons-io-2.2.jar
      commons-lang3-3.2.jar
      dom4j-1.6.1.jar
      freemarker-2.3.22.jar
      geronimo-jta_1.1_spec-1.1.1.jar
      hibernate-commons-annotations-5.0.1.Final.jar
      hibernate-core-5.0.7.Final.jar
      hibernate-jpa-2.1-api-1.0.0.Final.jar
      jandex-2.0.0.Final.jar
      javassist-3.18.1-GA.jar
      jboss-logging-3.3.0.Final.jar
      jstl-1.2.jar
      log4j-api-2.2.jar
      log4j-core-2.2.jar
      mysql-connector-java-5.1.7-bin.jar
      ognl-3.0.6.jar
      spring-aop-4.2.4.RELEASE.jar
      spring-aspects-4.2.4.RELEASE.jar
      spring-beans-4.2.4.RELEASE.jar
      spring-context-4.2.4.RELEASE.jar
      spring-core-4.2.4.RELEASE.jar
      spring-expression-4.2.4.RELEASE.jar
      spring-jdbc-4.2.4.RELEASE.jar
      spring-orm-4.2.4.RELEASE.jar
      spring-test-4.2.4.RELEASE.jar
      spring-tx-4.2.4.RELEASE.jar
      spring-web-4.2.4.RELEASE.jar
      standard.jar
      struts2-core-2.3.24.jar
      struts2-spring-plugin-2.3.24.jar
      xwork-core-2.3.24.jar

    2. 搭建基本的项目结构


      Snip20180824_1.png

    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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    
        <bean name="userAction" class="web.UserAction" scope="prototype"></bean>
    
        <bean name="userService" class="serviceImpl.UserServiceImpl"></bean>
    </beans>
    

    2. 整合Struts2到spring

    2.1 Struts和spring整合,需要配置的静态常量

    <!--spring负责装配Action依赖属性,默认struts已经打开了-->
        <!--<constant name="struts.objectFactory.spring.autoWire" value="name"></constant>-->
    
        <!--将action的创建交给spring容器-->
        <constant name="struts.objectFactory" value="spring"></constant>
    

    2.2 action交给spring管理的两种创建方式

    创建UserAction

    
    public class UserAction extends ActionSupport {
    
        private UserService userService;
    
        public String login() throws Exception {
    
            System.out.println(userService);
    
            return SUCCESS;
        }
    
        public void setUserService(UserService userService) {
            this.userService = userService;
        }
    }
    

    方式一:struts2自己创建action,spring负责组装依赖属性(了解)

    <?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>
    
        <!--spring负责装配Action依赖属性,默认struts已经打开了-->
        <!--<constant name="struts.objectFactory.spring.autoWire" value="name"></constant>-->
    
        <!--将action的创建交给spring容器-->
        <constant name="struts.objectFactory" value="spring"></constant>
    
        <package name="crm" namespace="/" extends="struts-default">
    
            <!-- 整合方案1:class属性上仍然配置action的完整类名
                          struts2仍然创建action,由spring负责组装Action中的依赖属性
            -->
            <action name="UserAction_*" class="web.UserAction" method="{1}">
                <result name="success" type="redirect">/success.jsp</result>
            </action>
        </package>
    
    </struts>
    

    方案二:spring负责创建action,需要手动在applicationContext.xml中配置action中对应的属性注入。

    applicationContext.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    
        <bean name="userAction" class="web.UserAction" scope="prototype">
            <property name="userService" ref="userService"></property>
        </bean>
    
        <bean name="userService" class="serviceImpl.UserServiceImpl"></bean>
    </beans>
    

    Struts2从spring中获取action。这里的获取依据是class="userAction",而不是类的完整类名。

    struts.xml

    <!-- 
                整合方案2:class属性上填写spring中action对象的BeanName
                    完全由spring管理action生命周期,包括Action的创建
                    注意:需要手动组装依赖属性
              -->
            <action name="UserAction_*" class="userAction" method="{1}" >
                <result name="toHome" type="redirect" >/index.htm</result>
                <result name="error" >/login.jsp</result>
            </action>
    

    3. hibernate整合到spring

    3.1 整合原理

    将sessionFactory交给spring来管理

    3.2 将SessionFactory配置到spring容器中

    方案一:(了解)
    在applicationContext.xml文件中进行配置
    这里,sessionFactory依然是从hibernate.cfg.xml配置文件中读取的

    <!--将sessionFactory配置到spring容器中-->
    
        <!-- 加载配置方案1:仍然使用外部的hibernate.cfg.xml配置信息 -->
        <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
            <property name="configLocation" value="hibernate.cfg.xml"></property>
        </bean>
    

    方案二:(推荐)
    在applicationContext.xml文件中进行配置
    这里直接在applicationContext.xml文件中进行hibernate的配置,不需要再使用hibernate.cfg.xml

    
     <!-- 加载配置方案2:在spring配置中放置hibernate配置信息 -->
        <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    
            <!-- 配置hibernate基本信息 -->
            <property name="hibernateProperties">
                <props>
                    <!--  必选配置 -->
                    <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
                    <prop key="hibernate.connection.url">jdbc:mysql://123.206.7.239/xiaobang</prop>
                    <prop key="hibernate.connection.username">root</prop>
                    <prop key="hibernate.connection.password">123456789</prop>
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    
                    <!--可选配置-->
                    <prop key="hibernate.show_sql">true</prop>
                    <prop key="hibernate.format_sql">true</prop>
                    <prop key="hibernate.hbm2ddl.auto">update</prop>
                </props>
            </property>
    
            <!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 -->
            <property name="mappingDirectoryLocations" value="classpath:domain"></property>
        </bean>
    

    3.4 通过读取db.properties文件,引入c3p0连接池

    1. 创建db.properties文件
    jdbc.jdbcUrl=jdbc:mysql://123.206.7.239/xiaobang
    jdbc.driverClass=com.mysql.jdbc.Driver
    jdbc.user=root
    jdbc.password=123456789
    

    在applicationContext.xml中进行配置

     <!--读取db.properties文件-->
        <context:property-placeholder location="classpath:db.properties"/>
    
        <!--配置c3p0数据库连接池-->
        <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
            <property name="driverClass" value="${jdbc.driverClass}"></property>
            <property name="user" value="${jdbc.user}"></property>
            <property name="password" value="${jdbc.password}"></property>
        </bean>
    
    
        <!--将sessionFactory配置到spring容器中-->
    
        <!-- 加载配置方案1:仍然使用外部的hibernate.cfg.xml配置信息 -->
        <!--<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">-->
            <!--<property name="configLocation" value="hibernate.cfg.xml"></property>-->
        <!--</bean>-->
    
        <!-- 加载配置方案2:在spring配置中放置hibernate配置信息 -->
        <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    
            <!-- 将连接池注入到sessionFactory, hibernate会通过连接池获得连接 -->
            <property name="dataSource" ref="dataSource"></property>
            
            <!-- 配置hibernate基本信息 -->
            <property name="hibernateProperties">
                <props>
                    <!--  必选配置 -->
                    <!--<prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>-->
                    <!--<prop key="hibernate.connection.url">jdbc:mysql://123.206.7.239/xiaobang</prop>-->
                    <!--<prop key="hibernate.connection.username">root</prop>-->
                    <!--<prop key="hibernate.connection.password">123456789</prop>-->
    
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    
                    <!--可选配置-->
                    <prop key="hibernate.show_sql">true</prop>
                    <prop key="hibernate.format_sql">true</prop>
                    <prop key="hibernate.hbm2ddl.auto">update</prop>
                </props>
            </property>
    
            <!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 -->
            <property name="mappingDirectoryLocations" value="classpath:domain"></property>
        </bean>
    

    3.5 使用HibernateTemplate模板操作数据库

    1. 在applicationContext.xml配置dao
    <!--dao-->
        <bean name="userDao" class="daoImpl.UserDaoImpl">
            <property name="sessionFactory" ref="sessionFactory"></property>
        </bean>
    
    1. UserDaoImpl中使用HibernateTemplate模板
      分别使用HQL和离线Criteria进行查询操作
    public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
    
    
        @Override
        public User findUser(User user) {
    
    //        return getHibernateTemplate().execute(new HibernateCallback<User>() {
    //
    //            @Override
    //             public User doInHibernate(Session session) throws HibernateException {
    //
    //                String hql = "from User where user_code = ?";
    //
    //                Query query = session.createQuery(hql);
    //
    //                query.setParameter(0, user.getUser_code());
    //
    //                User user1 = (User) query.uniqueResult();
    //
    //                return user1;
    //            }
    //        });
    
            //Criteria
            DetachedCriteria dc = DetachedCriteria.forClass(User.class);
    
            dc.add(Restrictions.eq("user_code", user.getUser_code()));
    
            List<User> list = (List<User>) getHibernateTemplate().findByCriteria(dc);
    
            if(list != null && list.size()>0){
                return list.get(0);
            }else{
                return null;
            }
    
        }
    }
    

    4.整合aop事务

    4.1 xml配置事务

    <!--==========================================================================================-->
    
        <!--配置核心事务管理器-->
        <bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"></property>
        </bean>
    
        <!--配置通知-->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
                <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
                <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
                <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
                <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
                <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
                <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
                <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
            </tx:attributes>
        </tx:advice>
    
        <!--配置将通知织入目标对象-->
        <aop:config>
            <aop:pointcut expression="execution(* serviceImpl.*ServiceImpl.*(..))" id="txPc"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />
        </aop:config>
    
    
    
        <!--==========================================================================================-->
    

    测试

    @Resource(name = "userService")
        private UserService userService;
        @Test
        public void testHibernate04() {
    
            User user = new User();
            user.setUser_code("rose");
    
            userService.save(user);
        }
    

    4.2 注解配置事务

    1. 在配置文件中开启使用注解事务
    <!--==========================================================================================-->
    
        <!--配置核心事务管理器-->
        <bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"></property>
        </bean>
    
        <!--配置通知-->
        <!--<tx:advice id="txAdvice" transaction-manager="transactionManager">-->
            <!--<tx:attributes>-->
                <!--<tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />-->
                <!--<tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />-->
                <!--<tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />-->
                <!--<tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />-->
                <!--<tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />-->
                <!--<tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />-->
                <!--<tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />-->
                <!--<tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />-->
            <!--</tx:attributes>-->
        <!--</tx:advice>-->
    
        <!--&lt;!&ndash;配置将通知织入目标对象&ndash;&gt;-->
        <!--<aop:config>-->
            <!--<aop:pointcut expression="execution(* serviceImpl.*ServiceImpl.*(..))" id="txPc"/>-->
            <!--<aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />-->
        <!--</aop:config>-->
    
    
        <!--开启注解事务-->
        <tx:annotation-driven transaction-manager="transactionManager"/>
    
        <!--==========================================================================================-->
    
    1. 在serviceImpl中使用注解
      在类上进行统一配置,在特殊方法上进行单独配置
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = true)
    public class UserServiceImpl implements UserService {
    
        private UserDao userDao;
    
        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }
    
        @Override
        public User findUser(User user) {
    
            Session session = HibernateUtils.getCurrentSession();
    
            // 开启事务
            session.beginTransaction();
    
            User findUser = userDao.findUser(user);
    
            // 提交事务
            session.getTransaction().commit();
    
            if (findUser == null) {
                throw  new RuntimeException("账户名不存在");
            }
    
            if (!findUser.getUser_password().equals(user.getUser_password())) {
                throw new RuntimeException("密码错误");
            }
    
            return findUser;
        }
    
    
        @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = false)
        public void save(User user) {
            userDao.save(user);
        }
    
    }
    

    5. 扩大session的作用范围

    为了避免hibernate使用懒加载的时候,出现no-session问题,需要扩大session的作用范围
    在web.xml文件中

    <!-- 扩大session作用范围
        注意: 任何filter一定要在struts的filter之前调用
       -->
        <filter>
            <filter-name>openSessionInViewFilter</filter-name>
            <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>openSessionInViewFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
    
        <!--配置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>
    

    相关文章

      网友评论

          本文标题:SSH项目_01三大框架的整合

          本文链接:https://www.haomeiwen.com/subject/yqeiiftx.html