spring入门之三


AOP :切面编程

       切面:切入点和通知结合

spring aop 编程

<aop:config>

方法1

  <aop:pointcut expression="切入点表达式" id="">

  <aop:advisor  advice-ref="通知引用" pointcut-ref="切入点的引用">

 

方法2

   <aop:advisor  advice-ref="通知引用" pointcut="切入点表达式">

 

AspectJ xml

<aop:config>

  <aop:aspect ref="切面类">

     <aop:pointcut>

     <aop:before>  前置

     <aop:afterReturning  returning="第二个参数名称"> 后置

     <aop:around> 环绕

     <aop:afterThrowing throwing="第二。。。"> 抛出异常

     <aop:after> 最终

 

AspectJ annotation

       @Aspect

       @Pointcut("表达式")  private void xxx(){}

       @Before @...

 

l  切入点表达式

       <aop:pointcutexpression="execution(* com.itheima.crm.*.service..*.*(..))"id="">

 

2       事务管理

2.1  回顾事务

l  事务:一组业务操作ABCD,要么全部成功,要么全部不成功。

l  特性:ACID

       原子性:整体

       一致性:完成

       隔离性:并发

       持久性:结果

l  隔离问题:

       脏读:一个事务读到另一个事务没有提交的数据

       不可重复读:一个事务读到另一个事务已提交的数据(update

       虚读(幻读):一个事务读到另一个事务已提交的数据(insert

l  隔离级别:

       readuncommitted:读未提交。存在3个问题

       readcommitted:读已提交。解决脏读,存在2个问题

       repeatableread:可重复读。解决:脏读、不可重复读,存在1个问题。

       serializable:串行化。都解决,单事务。

      

mysql 事务操作--简单

ABCD 一个事务

Connection conn = null;

try{

  //1 获得连接

  conn = ...;

  //2 开启事务

  conn.setAutoCommit(false);

  A

  B

  C

  D

  //3 提交事务

  conn.commit();

} catche(){

  //4 回滚事务

  conn.rollback();

}

 

mysql 事务操作--Savepoint

需求:AB(必须),CD(可选)

Connection conn = null;

Savepoint savepoint = null;  //保存点,记录操作的当前位置,之后可以回滚到指定的位置。(可以回滚一部分)

try{

  //1 获得连接

  conn = ...;

  //2 开启事务

  conn.setAutoCommit(false);

  A

  B

  savepoint = conn.setSavepoint();

  C

  D

  //3 提交事务

  conn.commit();

} catche(){

  if(savepoint != null){   //CD异常

     // 回滚到CD之前

     conn.rollback(savepoint);

     // 提交AB

     conn.commit();

  } else{   //AB异常

     // 回滚AB

     conn.rollback();

  }

}

 

2.2  事务管理介绍

2.2.1   导入jar

transaction -->  tx

 

2.2.2   三个顶级接口

PlatformTransactionManager  平台事务管理器,spring要管理事务,必须使用事务管理器

       进行事务配置时,必须配置事务管理器

TransactionDefinition:事务详情(事务定义、事务属性),spring用于确定事务具体详情,

       例如:隔离级别、是否只读、超时时间等

       进行事务配置时,必须配置详情spring将配置项封装到该对象实例。

TransactionStatus:事务状态,spring用于记录当前事务运行状态。例如:是否有保存点,事务是否完成。

       spring底层根据状态进行相应操作。

 

2.2.3   PlatformTransactionManager  事务管理器

l  导入jar包:需要时平台事务管理器的实现类

      

 

l  常见的事务管理器

       DataSourceTransactionManager  jdbc开发时事务管理器,采用JdbcTemplate

       HibernateTransactionManagerhibernate开发时事务管理器,整合hibernate

 

api详解

TransactionStatusgetTransaction(TransactionDefinition definition) ,事务管理器通过“事务详情”,获得“事务状态”,从而管理事务。

void commit(TransactionStatus status)  根据状态提交

void rollback(TransactionStatus status) 根据状态回滚

 

2.2.4   TransactionStatus

 

 

2.2.5   TransactionDefinition

l  传播行为:在两个业务之间如何共享事务。

 

PROPAGATION_REQUIRED , required , 必须 【默认值】

       支持当前事务,A如果有事务,B将使用该事务。

       如果A没有事务,B将创建一个新的事务。

PROPAGATION_SUPPORTS supports ,支持

       支持当前事务,A如果有事务,B将使用该事务。

       如果A没有事务,B将以非事务执行。

PROPAGATION_MANDATORYmandatory ,强制

       支持当前事务,A如果有事务,B将使用该事务。

       如果A没有事务,B将抛异常。

PROPAGATION_REQUIRES_NEW requires_new ,必须新的

       如果A有事务,将A的事务挂起,B创建一个新的事务

       如果A没有事务,B创建一个新的事务

PROPAGATION_NOT_SUPPORTED not_supported ,不支持

       如果A有事务,将A的事务挂起,B将以非事务执行

       如果A没有事务,B将以非事务执行

PROPAGATION_NEVER never,从不

       如果A有事务,B将抛异常

       如果A没有事务,B将以非事务执行

PROPAGATION_NESTED nested ,嵌套

       AB底层采用保存点机制,形成嵌套事务。

 

掌握:PROPAGATION_REQUIREDPROPAGATION_REQUIRES_NEWPROPAGATION_NESTED

 

 

 

 

2.3  案例:转账

2.3.1   搭建环境

2.3.1.1        创建表

create database ee19_spring_day03;

use ee19_spring_day03;

create table account(

  id int primary key auto_increment,

  username varchar(50),

  money int

);

insert into account(username,money) values('jack','10000');

insert into account(username,money) values('rose','10000');

 

2.3.1.2        导入jar

l  核心:4+1

aop 4 (aop联盟、spring aopaspectj规范、spring aspect)

l  数据库:jdbc/tx

l  驱动:mysql

l  连接池:c3p0

 

 

2.3.1.3        dao

publicclass AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

 

   @Override

   publicvoid out(String outer, Integer money) {

      this.getJdbcTemplate().update("update account set money = money - ? where username = ?", money,outer);

   }

 

   @Override

   publicvoid in(String inner, Integer money) {

      this.getJdbcTemplate().update("update account set money = money + ? where username = ?", money,inner);

   }

 

}

 

2.3.1.4        service

publicclass AccountServiceImpl implements AccountService {

 

   private AccountDao accountDao;

   publicvoid setAccountDao(AccountDao accountDao) {

      this.accountDao = accountDao;

   }

   @Override

   publicvoid transfer(String outer, String inner, Integer money) {

      accountDao.out(outer, money);

      //断电

//    int i = 1/0;

      accountDao.in(inner, money);

   }

 

}

 

 

2.3.1.5        spring配置

    <!-- 1 datasource -->

    <beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource">

        <propertyname="driverClass"value="com.mysql.jdbc.Driver"></property>

        <propertyname="jdbcUrl"value="jdbc:mysql://localhost:3306/ee19_spring_day03"></property>

        <propertyname="user"value="root"></property>

        <propertyname="password"value="1234"></property>

    </bean>

   

    <!-- 2 dao  -->

    <beanid="accountDao"class="com.itheima.dao.impl.AccountDaoImpl">

        <propertyname="dataSource"ref="dataSource"></property>

    </bean>

    <!-- 3 service -->

    <beanid="accountService"class="com.itheima.service.impl.AccountServiceImpl">

        <propertyname="accountDao"ref="accountDao"></property>

    </bean>

 

2.3.1.6        测试

    @Test

    publicvoid demo01(){

        String xmlPath = "applicationContext.xml";

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);

        AccountService accountService =  (AccountService) applicationContext.getBean("accountService");

        accountService.transfer("jack", "rose", 1000);

    }

 

2.3.2   手动管理事务(了解)

spring底层使用TransactionTemplate 事务模板进行操作。

l  操作

1.service 需要获得 TransactionTemplate

2.spring 配置模板,并注入给service

3.模板需要注入事务管理器

4.配置事务管理器:DataSourceTransactionManager ,需要注入DataSource

 

2.3.2.1        修改service

    //需要spring注入模板

    private TransactionTemplate transactionTemplate;

    publicvoid setTransactionTemplate(TransactionTemplate transactionTemplate) {

        this.transactionTemplate = transactionTemplate;

    }

    @Override

    publicvoid transfer(final String outer,final String inner,final Integer money) {

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

           

            @Override

            protectedvoid doInTransactionWithoutResult(TransactionStatus arg0) {

                accountDao.out(outer, money);

                //断电

//              int i = 1/0;

                accountDao.in(inner, money);

            }

        });

 

    }

 

2.3.2.2        修改spring配置

<!-- 3 service -->

    <beanid="accountService"class="com.itheima.service.impl.AccountServiceImpl">

        <propertyname="accountDao"ref="accountDao"></property>

        <propertyname="transactionTemplate"ref="transactionTemplate"></property>

    </bean>

   

    <!-- 4 创建模板 -->

    <beanid="transactionTemplate"class="org.springframework.transaction.support.TransactionTemplate">

        <propertyname="transactionManager"ref="txManager"></property>

    </bean>

   

    <!-- 5 配置事务管理器 ,管理器需要事务,事务从Connection获得,连接从连接池DataSource获得 -->

    <beanid="txManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <propertyname="dataSource"ref="dataSource"></property>

    </bean>

 

 

2.3.3   工厂bean 生成代理:半自动

spring提供管理事务的代理工厂bean TransactionProxyFactoryBean

1.getBean() 获得代理对象

2.spring 配置一个代理

 

2.3.3.1        spring配置

<!-- 4 service 代理对象

        4.1 proxyInterfaces 接口

        4.2 target 目标类

        4.3 transactionManager 事务管理器

        4.4 transactionAttributes 事务属性(事务详情)

            prop.key :确定哪些方法使用当前事务配置

            prop.text:用于配置事务详情

                格式:PROPAGATION,ISOLATION,readOnly,-Exception,+Exception

                    传播行为     隔离级别是否只读     异常回滚     异常提交

                例如:

                    <prop key="transfer">PROPAGATION_REQUIRED,ISOLATION_DEFAULT</prop> 默认传播行为,和隔离级别

                    <prop key="transfer">PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly</prop> 只读

                    <prop key="transfer">PROPAGATION_REQUIRED,ISOLATION_DEFAULT,+java.lang.ArithmeticException</prop>  有异常扔提交

    -->

    <beanid="proxyAccountService"class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">

        <propertyname="proxyInterfaces"value="com.itheima.service.AccountService"></property>

        <propertyname="target"ref="accountService"></property>

        <propertyname="transactionManager"ref="txManager"></property>

        <propertyname="transactionAttributes">

            <props>

                <propkey="transfer">PROPAGATION_REQUIRED,ISOLATION_DEFAULT</prop>

            </props>

        </property>

    </bean>

 

 

    <!-- 5 事务管理器 -->

    <beanid="txManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <propertyname="dataSource"ref="dataSource"></property>

    </bean>

   

 

 

2.3.3.2        测试

 

 

2.3.4   AOP 配置基于xml【掌握】

l  在spring xml 配置aop 自动生成代理,进行事务的管理

1.配置管理器

2.配置事务详情

3.配置aop

 

<!-- 4 事务管理 -->

    <!-- 4.1 事务管理器 -->

    <beanid="txManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <propertyname="dataSource"ref="dataSource"></property>

    </bean>

    <!-- 4.2 事务详情(事务通知)  aop筛选基础上,对ABC三个确定使用什么样的事务。例如:AC读写、B只读

        <tx:attributes> 用于配置事务详情(属性属性)

            <tx:method name=""/> 详情具体配置

                propagation 传播行为 REQUIRED:必须;REQUIRES_NEW:必须是新的

                isolation 隔离级别

    -->

    <tx:adviceid="txAdvice"transaction-manager="txManager">

        <tx:attributes>

            <tx:methodname="transfer"propagation="REQUIRED"isolation="DEFAULT"/>

        </tx:attributes>

    </tx:advice>

    <!-- 4.3 AOP编程,目标类有ABCD4个连接点),切入点表达式确定增强的连接器,从而获得切入点:ABC -->

    <aop:config>

        <aop:advisoradvice-ref="txAdvice"pointcut="execution(* com.itheima.service..*.*(..))"/>

    </aop:config>

 

 

2.3.5   AOP配置基于注解【掌握】

1.配置事务管理器,将并事务管理器交予spring

2.在目标类或目标方法添加注解即可 @Transactional

 

 

2.3.5.1        spring配置

<!-- 4 事务管理 -->

    <!-- 4.1 事务管理器 -->

    <beanid="txManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <propertyname="dataSource"ref="dataSource"></property>

    </bean>

    <!-- 4.2 将管理器交予spring

        * transaction-manager 配置事务管理器

        * proxy-target-class

            true 底层强制使用cglib代理

    -->

    <tx:annotation-driventransaction-manager="txManager"/>

 

2.3.5.2        service

@Transactional

publicclass AccountServiceImpl implements AccountService {

 

2.3.5.3        事务详情配置

 

@Transactional(propagation=Propagation.REQUIRED , isolation = Isolation.DEFAULT)

publicclass AccountServiceImpl implements AccountService {

 

 

3       整合Junit

l  导入jar

       基本:4+1

       测试:spring-test...jar

 

1.Junit通知spring加载配置文件

2.spring容器自动进行注入

 

l  修改测试类

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations="classpath:applicationContext.xml")

publicclass TestApp {

   

    @Autowired  //junit整合,不需要在spring xml配置扫描

    private AccountService accountService;

   

    @Test

    publicvoid demo01(){

//      String xmlPath = "applicationContext.xml";

//      ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);

//      AccountService accountService =  (AccountService) applicationContext.getBean("accountService");

        accountService.transfer("jack", "rose", 1000);

    }

 

}

 

4       整合web

0.导入jar

       spring-web.xml

      

1.tomcat启动加载配置文件

       servlet--> init(ServletConfig) --> <load-on-startup>2

       filter--> init(FilterConfig)  --> web.xml注册过滤器自动调用初始化

       listener--> ServletContextListener --> servletContext对象监听【】

       spring提供监听器ContextLoaderListener  --> web.xml  <listener><listener-class>....

              如果只配置监听器,默认加载xml位置:/WEB-INF/applicationContext.xml

             

2.确定配置文件位置,通过系统初始化参数

       ServletContext初始化参数web.xml 

              <context-param>

                     <param-name>contextConfigLocation

                     <param-value>classpath:applicationContext.xml

 

  <!-- 确定配置文件位置 -->

  <context-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>classpath:applicationContext.xml</param-value>

  </context-param>

 

  <!-- 配置spring 监听器加载xml配置文件 -->

  <listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  </listener>

 

3.servletContext作用域获得spring容器(了解)

    // application作用域(ServletContext)获得spring容器

        //方式1手动从作用域获取

        ApplicationContext applicationContext =

                (ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

        //方式2:通过工具获取

        ApplicationContext apppApplicationContext2 =

                WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());

       

 

 

5       SSH整合

5.1  jar整合

struts2.3.15.3

hibernate : 3.6.10

spring: 3.2.0

 

5.1.1   struts

struts-2.3.15.3\apps\struts2-blank\WEB-INF\lib

 

模板技术  ,一般用于页面静态化

freemarker:扩展名:*.ftl

velocity :扩展名  *.vm

5.1.2   spring

l  基础:4+1 beanscorecontextexpression commons-logging (struts已经导入)

AOPaop联盟、spring aop aspect规范、spring aspect

dbjdbctx

l  测试:test

web开发:spring web

 

l  驱动:mysql

l  连接池:c3p0

 

l  整合hibernatespring orm

 

 

5.1.3   hibernate

%h%\hibernate3.jar                     核心

%h%\lib\required                 必须

      

%h%\lib\jpa                        jpa规范(java persistent api 持久api),hibernate注解开发 @Entity @Id

 

l 整合log4j

       导入 log4j...jar (struts已经导入)

       整合(过渡):slf4j-log4j12-1.7.5.jar

      

l 二级缓存

       核心:ehcache-1.5.0.jar

       依赖:

              backport-util-concurrent-2.1.jar

              commons-logging  (存在)

 

5.1.4  整合包

spring整合hibernatespring orm

struts整合springstruts2-spring-plugin-2.3.15.3.jar

 

删除重复jar

 

 

5.2  spring整合hibernate:有hibernate.cfg.xml

5.2.1  创建表

create table t_user(

  id int primary key auto_increment,

  username varchar(50),

  password varchar(32),

  age int

);

 

5.2.2  PO

javabean

publicclass User {

   private Integer id;

   private String username;

   private String password;

   private Integer age;

 

l 映射文件

<!DOCTYPEhibernate-mappingPUBLIC

    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

    <classname="com.itheima.domain.User" table="t_user">

        <idname="id">

            <generatorclass="native"></generator>

        </id>

        <propertyname="username"></property>

        <propertyname="password"></property>

        <propertyname="age"></property>

    </class>

 

</hibernate-mapping>

 

5.2.3  dao

spring提供 HibernateTemplate 用于操作PO对象,类似Hibernate Session对象。

 

publicclass UserDaoImpl implements UserDao {

   

    //需要spring注入模板

    private HibernateTemplate hibernateTemplate;

    publicvoid setHibernateTemplate(HibernateTemplate hibernateTemplate) {

        this.hibernateTemplate = hibernateTemplate;

    }

 

    @Override

    publicvoid save(User user) {

        this.hibernateTemplate.save(user);

    }

 

}

 

5.2.4  service

 

publicclass UserServiceImpl implements UserService {

 

    private UserDao userDao;

    publicvoid setUserDao(UserDao userDao) {

        this.userDao = userDao;

    }

    @Override

    publicvoid register(User user) {

        userDao.save(user);

    }

 

}

 

 

 

5.2.5  hibernate.cfg.xml

<session-factory>

        <!-- 1基本4 -->

        <propertyname="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

        <propertyname="hibernate.connection.url">jdbc:mysql:///ee19_spring_day03</property>

        <propertyname="hibernate.connection.username">root</property>

        <propertyname="hibernate.connection.password">1234</property>

       

        <!-- 2 配置方言 -->

        <propertyname="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

       

        <!-- 3 sql语句 -->

        <propertyname="hibernate.show_sql">true</property>

        <propertyname="hibernate.format_sql">true</property>

       

        <!-- 4 自动生成表(一般没用) -->

        <propertyname="hibernate.hbm2ddl.auto">update</property>

       

        <!-- 5本地线程绑定 -->

        <propertyname="hibernate.current_session_context_class">thread</property>

       

        <!-- 导入映射文件 -->

        <mappingresource="com/itheima/domain/User.hbm.xml"/>

   

    </session-factory>

 

5.2.6  applicationContext.xml

5.2.6.1        添加命名空间

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="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">

 

 

5.2.6.2        加载hibernate配置文件

<!-- 1 加载hibenrate.cfg.xml 获得SessionFactory

        * configLocation确定配置文件位置

    -->

    <beanid="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

        <propertyname="configLocation"value="classpath:hibernate.cfg.xml"></property>

    </bean>

   

    <!-- 2创建模板

        * 底层使用sessionsession sessionFactory获得

    -->

    <beanid="hibernateTemplate"class="org.springframework.orm.hibernate3.HibernateTemplate">

        <propertyname="sessionFactory"ref="sessionFactory"></property>

    </bean>

 

5.2.6.3        daoservice

<!-- 3 dao -->

    <beanid="userDao"class="com.itheima.dao.impl.UserDaoImpl">

        <propertyname="hibernateTemplate"ref="hibernateTemplate"></property>

    </bean>

   

    <!-- 4 service -->

    <beanid="userService"class="com.itheima.service.impl.UserServiceImpl">

        <propertyname="userDao"ref="userDao"></property>

    </bean>

 

5.2.6.4        事务管理

<!-- 5 事务管理 -->

    <!-- 5.1 事务管理器HibernateTransactionManager -->

    <beanid="txManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">

        <propertyname="sessionFactory"ref="sessionFactory"></property>

    </bean>

    <!-- 5.2 事务详情,给ABC进行具体事务设置 -->

    <tx:adviceid="txAdvice"transaction-manager="txManager">

        <tx:attributes>

            <tx:methodname="register"/>

        </tx:attributes>

    </tx:advice>

    <!-- 5.3 AOP编程,ABCD 筛选ABC  -->

    <aop:config>

        <aop:advisoradvice-ref="txAdvice"pointcut="execution(* com.itheima.service..*.*(..))"/>

    </aop:config>

 

 

5.2.7  测试

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations="classpath:applicationContext.xml")

publicclass TestApp {

  

   @Autowired

   private UserService userService;

  

   @Test

   publicvoid demo01(){

      User user = new User();

      user.setUsername("jack");

      user.setPassword("1234");

      user.setAge(18);

     

      userService.register(user);

   }

}

 

 

 

5.3  spring整合hibernate:没有hibernate.cfg.xml【】

l 删除hibernate.cfg.xml文件,但需要保存文件内容,将其配置spring

l 修改dao层,继承HibernateDaoSupport

 

5.3.1  修改spring,配置SessionFactory

<!-- 1.1加载properties文件 -->

    <!-- 1.2 配置数据源 -->

    <beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource">

        <propertyname="driverClass"value="com.mysql.jdbc.Driver"></property>

        <propertyname="jdbcUrl"value="jdbc:mysql:///ee19_spring_day03"></property>

        <propertyname="user"value="root"></property>

        <propertyname="password"value="1234"></property>

    </bean>

   

    <!-- 1.3配置 LocalSessionFactoryBean,获得SessionFactory

        * configLocation确定配置文件位置

            <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>

        1)dataSource 数据源

        2)hibernateProperties hibernate其他配置项

        3) 导入映射文件

            mappingLocations ,确定映射文件位置,需要classpath:” ,支持通配符【】

                <property name="mappingLocations" value="classpath:com/itheima/domain/User.hbm.xml"></property>

                <property name="mappingLocations" value="classpath:com/itheima/domain/*.hbm.xml"></property>

            mappingResources ,加载执行映射文件,从src下开始。不支持通配符*

                <property name="mappingResources" value="com/itheima/domain/User.hbm.xml"></property>

            mappingDirectoryLocations ,加载指定目录下的,所有配置文件

                <property name="mappingDirectoryLocations" value="classpath:com/itheima/domain/"></property>

            mappingJarLocations jar包中获得映射文件

    -->

    <beanid="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

        <propertyname="dataSource"ref="dataSource"></property>

        <propertyname="hibernateProperties">

            <props>

                <propkey="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>

                <propkey="hibernate.show_sql">true</prop>

                <propkey="hibernate.format_sql">true</prop>

                <propkey="hibernate.hbm2ddl.auto">update</prop>

                <propkey="hibernate.current_session_context_class">thread</prop>

            </props>

        </property>

        <propertyname="mappingLocations"value="classpath:com/itheima/domain/*.hbm.xml"></property>

    </bean>

 

 

5.3.2  修改dao,使用HibernateDaoSupport

l 继承HibernateDaoSupport

// 底层需要SessionFactory,自动创建HibernateTemplate模板

publicclass UserDaoImpl extends HibernateDaoSupport implements UserDao {

 

   @Override

   publicvoid save(User user) {

      this.getHibernateTemplate().save(user);

   }

 

}

spring删除模板,给dao注入SessionFactory

   <!-- 3 dao -->

   <beanid="userDao"class="com.itheima.dao.impl.UserDaoImpl">

      <propertyname="sessionFactory"ref="sessionFactory"></property>

   </bean>

 

 

 

5.4  struts整合springspring创建action

1.编写action类,并将其配置给spring spring可以注入service

2.编写struts.xml

3.表单jsp页面

4.web.xml 配置

       1.确定配置文件contextConfigLocation

       2.配置监听器ContextLoaderListener

       3.配置前端控制器 StrutsPrepareAndExecuteFitler

 

5.4.1  action

l 通用

publicclass UserAction extends ActionSupport implements ModelDriven<User> {

 

   //1 封装数据

   private User user = new User();

 

   @Override

   public User getModel() {

      returnuser;

   }

  

   //2 service

   private UserService userService;

   publicvoid setUserService(UserService userService) {

      this.userService = userService;

   }

 

l 功能

/**

    * 注册

    * @return

    */

   public String register(){

      userService.register(user);

      return"success";

   }

 

5.4.2  spring配置

<!-- 6 配置action -->

    <beanid="userAction"class="com.itheima.web.action.UserAction"scope="prototype">

        <propertyname="userService"ref="userService"></property>

    </bean>

 

 

5.4.3  struts配置

<struts>

    <!-- 开发模式 -->

    <constantname="struts.devMode"value="true"/>

 

    <packagename="default"namespace="/"extends="struts-default">

    <!-- 底层自动从spring容器中通过名称获得内容, getBean("userAction") -->

    <actionname="userAction_*"class="userAction"method="{1}">

         <resultname="success">/messag.jsp</result>

    </action>

    </package>

</struts>

 

5.4.4  jsp表单

<formaction="${pageContext.request.contextPath}/userAction_register"method="post">

      用户名:<inputtype="text"name="username"/><br/>

      密码:<inputtype="password"name="password"/><br/>

      年龄:<inputtype="text"name="age"/><br/>

      <inputtype="submit"/>

   </form>

 

5.4.5  配置web.xml

<!-- 1 确定spring xml位置 -->

  <context-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>classpath:applicationContext.xml</param-value>

  </context-param>

  <!-- 2 spring监听器 -->

  <listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  </listener>

  <!-- 3 struts 前端控制器 -->

  <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>

 

 

5.5  struts整合springstruts创建action【】

l 删除spring action配置

struts<action class="全限定类名">

 

<packagename="default"namespace="/"extends="struts-default">

    <!-- 底层自动从spring容器中通过名称获得内容, getBean("userAction") -->

    <actionname="userAction_*"class="com.itheima.web.action.UserAction"method="{1}">

         <resultname="success">/messag.jsp</result>

    </action>

    </package>

 

l 要求:Action类中,必须提供service名称与spring配置文件一致。(如果名称一样,将自动注入)

      分析:

1. struts 配置文件

       default.properties  ,常量配置文件

       struts-default.xml ,默认核心配置文件

       struts-plugins.xml ,插件配置文件

       struts.xml,自定义核心配置文件

       常量的使用,后面配置项,将覆盖前面的。

2.default.properties  ,此配置文件中确定按照【名称】自动注入

       /org/apache/struts2/default.properties

      

3. struts-plugins.xml,struts整合 spring
  <constantname="struts.objectFactory" value="spring" />

       strutsaction将有spring创建

 

总结,之后actionspring创建,并按照名称自动注入


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值