spring(jdbc,hibernate,struts整合)

本文介绍Spring框架整合JDBC、Hibernate及Struts的具体步骤与实践案例,包括连接池配置、DAO层设计模式应用、Struts2-Spring插件原理分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Spring整合JDBC(基于数据库连接池)

  1)Spring框架对数据库访问技术提供了以下几点支持
  --提供了编写DAO的工具类DaoSupport,Template
  --提供了一致的异常处理层次DataAccessException
  --提供了声明式事务管理方法(基于AOP方式配置控制事务)

  2)Spring整合JDBC的步骤(示例见SpringTest02)


   --引入Spring开发包和配置

     引入JDBC开发包

   --根据COST表编写实体类

   --定义CostDao接口,编写实现类并继承JdbcDaoSupport,在实现类的增删改查方法中,利用super.getJdbcTemplate()工具完成相应操作

[java]  view plain  copy
  1. @Repository("jdbcCostDAO")  
  2. // @Scope("singleton")// 默认情况是单例  
  3. public class JdbcCostDAO extends JdbcDaoSupport implements ICostDao {  
  4.   
  5.     @Resource  
  6.     // 将容器中的dataSource给DAOSupport注入  
  7.     public void setMyDataSource(DataSource ds) {  
  8.         super.setDataSource(ds);// DaoSupport利用ds实例化template对象,使得getJdbcTemplate()可以获取连接  
  9.     }  
  10.   
  11.     @Override  
  12.     public List<Cost> findAll() throws DataAccessException {  
  13.         String sql = "select * from COST";  
  14.         CostMapper mapper = new CostMapper();  
  15.         List<Cost> list = super.getJdbcTemplate().query(sql, mapper);  
  16.         return list;  
  17.     }  
  18.   
  19.     @Override  
  20.     public List<Cost> findByPage(int page, int pageSize)  
  21.             throws DataAccessException {  
  22.         String sql = "select ID,NAME,BASE_DURATION,BASE_COST,UNIT_COST,STATUS,DESCR,CREATIME,STARTIME,COST_TYPE from(select ID,NAME,BASE_DURATION,BASE_COST,UNIT_COST,STATUS,DESCR,CREATIME,STARTIME,COST_TYPE,rownum n from COST  where rownum <? order by ID)where n>?";// 分页  
  23.         // 算当前页最大行:当前页数2*每页显示5=当前最大行10  
  24.         // 小于下一页的最小行  
  25.         int nextMin = page * pageSize + 1;  
  26.         // 大于上一页的最大行  
  27.         int lastMax = (page - 1) * pageSize;  
  28.         Object[] params = { nextMin, lastMax };  
  29.         CostMapper mapper = new CostMapper();  
  30.         List<Cost> list = super.getJdbcTemplate().query(sql, params, mapper);  
  31.         return list;  
  32.     }  
  33.   
  34.     @Override  
  35.     public int findTotalPage(int pageSize) throws DataAccessException {  
  36.         String sql = "select count(*) from COST";  
  37.         int size = super.getJdbcTemplate().queryForInt(sql);  
  38.         if (size % pageSize == 0) {  
  39.             return size / pageSize;  
  40.         } else {  
  41.             return size / pageSize + 1;  
  42.         }  
  43.     }  
  44.   
  45.     @Override  
  46.     public void deleteById(Integer id) throws DataAccessException {  
  47.         String sql = "delete from COST where ID=?";  
  48.         Object[] params = { id };  
  49.         super.getJdbcTemplate().update(sql, params);  
  50.     }  
  51.   
  52.     @Override  
  53.     public Cost findByName(String feeName) throws DataAccessException {  
  54.         String sql = "select * from COST where NAME=?";  
  55.         Object[] params = { feeName };  
  56.         CostMapper mapper = new CostMapper();  
  57.         Cost cost = (Cost) super.getJdbcTemplate().queryForObject(sql, params,  
  58.                 mapper);  
  59.         return cost;  
  60.     }  
  61.   
  62.     @Override  
  63.     public Cost findById(Integer id) throws DataAccessException {  
  64.         String sql = "select * from COST where ID=?";  
  65.         Object[] params = { id };  
  66.         CostMapper mapper = new CostMapper();  
  67.         Cost cost = (Cost) super.getJdbcTemplate().queryForObject(sql, params,  
  68.                 mapper);  
  69.         return cost;  
  70.     }  
  71.   
  72.     @Override  
  73.     public void updateCost(Cost cost) throws DataAccessException {  
  74.         String sql = "update cost set name=?,base_duration=?,"  
  75.                 + "base_cost=?,unit_cost=?,cost_type=?,descr=? " + "where id=?";  
  76.         Object[] params = { cost.getName(), cost.getBaseDuration(),  
  77.                 cost.getBaseCost(), cost.getUnitCost(), cost.getCostType(),  
  78.                 cost.getDescr(), cost.getId() };  
  79.         super.getJdbcTemplate().update(sql, params);  
  80.     }  
  81.   
  82. }  

CostMapper.java:

[java]  view plain  copy
  1. public class CostMapper implements RowMapper{  
  2.     //将rs中当前游标指定的记录转换成实体对象  
  3.     public Object mapRow(ResultSet rs, int index) throws SQLException {  
  4.         Cost c = new Cost();  
  5.         c.setId(rs.getInt("id"));  
  6.         c.setName(rs.getString("name"));  
  7.         c.setBaseDuration(rs.getInt("base_duration"));  
  8.         c.setBaseCost(rs.getDouble("base_cost"));  
  9.         c.setUnitCost(rs.getDouble("unit_cost"));  
  10.         c.setStatus(rs.getString("status"));  
  11.         c.setDescr(rs.getString("descr"));  
  12.         c.setCreateTime(rs.getDate("creatime"));  
  13.         c.setStartTime(rs.getDate("startime"));  
  14.         c.setCostType(rs.getString("cost_type"));  
  15.         return c;  
  16.     }  
  17. }  

   --将CostDao实现组件扫描到Spring容器

   --在Spring容器定义一个连接池对象(需引入连接池开发包[dbcp+数据库驱动],在Spring配置中添加dataSource组件定义),然后将连接池对象给CostDao注入,目是为JdbcTemplate设置Connection连接资源.(方法:在Dao中定义一个setXXX方法,接收注入的DataSource对象,然后给DaoSupport传入)

applicationContext.xml:

[html]  view plain  copy
  1. <span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
  4.     xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  6.                         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  7.                         http://www.springframework.org/schema/aop   
  8.                         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  9.                         http://www.springframework.org/schema/context   
  10.                         http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  11.                         http://www.springframework.org/schema/tx   
  12.                         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  13.     ">  
  14.   
  15.     <!-- 开启组件扫描 -->  
  16.     <context:component-scan base-package="com.test"></context:component-scan>  
  17.     <!-- 定义一个连接池对象dataSource -->  
  18.     <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource">  
  19.         <property name="username" value="system"></property>  
  20.         <property name="password" value="123456"></property>  
  21.         <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>  
  22.         <property name="url" value="jdbc:oracle:thin:@localhost:1521:test"></property>  
  23.         <property name="maxActive" value="20"></property><!-- 最大连接数 -->  
  24.         <property name="initialSize" value="1"></property><!-- 初始连接数 -->  
  25.     </bean>  
  26. </beans></span>  

   --测试Dao方法

[java]  view plain  copy
  1. @Test  
  2. public void test1() {  
  3.     String conf = "/applicationContext.xml";  
  4.     ApplicationContext ac = new ClassPathXmlApplicationContext(conf);  
  5.   
  6.     ICostDao costDao = (ICostDao) ac.getBean("jdbcCostDAO");  
  7.         //costDao.deleteById(122);  
  8.     List<Cost> list = costDao.findAll();  
  9.     for (Cost c : list) {  
  10.         System.out.println(c.getId() + " " + c.getName());  
  11.     }  
  12. }  

  3)JdbcTemplate API的使用
  --update() 用于执行增删改SQL语句
  --queryForObject() 用于执行查询一行结果的SQL
  --query() 用于执行查询多行结果的SQL
  --queryForInt() 用于查询返回一个数值的SQL

PS:连接池概念和优点
连接池是用于管理数据库Connection对象的工具,它可以将Connection对象数量控制在一个安全范围内。连接池中的Connection对象始终与数据库保持联通,避免频繁的创建和释放连接。

2.Spring整合Hibenrate

    (示例见SpringTest03)


  a.引入开发包
    Spring,Hibernate,数据库驱动

  b.根据COST表编写实体类和hbm.xml

hbm.xml:

[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC  
  3.     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  5. <hibernate-mapping>  
  6.     <!-- 通过class指定实体类和表的关系 -->  
  7.     <class name="com.test.pojo.Cost" table="cost" dynamic-update="true">  
  8.         <!-- 通过id元素指定主键属性和字段的关系: name:指定主键属性 column:指定主键字段 -->  
  9.         <id name="id" type="integer" column="id">  
  10.             <!-- 用来指明主键的生成方式 -->  
  11.             <generator class="sequence">  
  12.                 <param name="sequence">cost_seq</param>  
  13.             </generator>  
  14.         </id>  
  15.         <!-- 通过property元素指定属性和字段的关系: name:指定的是实体类中的属性 column:指定都是表中的字段 type:指定的是属性与字段转换时的类型 -->  
  16.         <property name="name" type="string" column="name" />  
  17.         <property name="baseDuration" type="integer" column="base_duration" />  
  18.         <property name="baseCost" type="double" column="base_cost" />  
  19.         <property name="unitCost" type="double" column="unit_cost" />  
  20.         <property name="status" type="string" column="status" />  
  21.         <property name="descr" type="string" column="descr" />  
  22.         <property name="createTime" type="date" column="creatime" />  
  23.         <property name="startTime" type="date" column="startime" />  
  24.         <property name="costType" type="string" column="cost_type" />  
  25.   
  26.     </class>  
  27. </hibernate-mapping>  

  c.定义DAO接口,根据接口编写实现类(继承HibernateDaoSupport,使用HibernateTemplate)

    --HibernateTemplate提供了增删改查处理方法。save()、delete()、updata()、load()、get()、find()

[java]  view plain  copy
  1. @Repository("hibernateCostDAO")  
  2. // @Scope("singleton")// 默认情况是单例  
  3. public class HibernateCostDAO extends HibernateDaoSupport implements ICostDao {  
  4.   
  5.     @Resource  
  6.     public void setMySessionFactory(SessionFactory sf) {  
  7.         // 将注入的sessionFactory,用于实例化template  
  8.         super.setSessionFactory(sf);  
  9.     }  
  10.   
  11.     @Override  
  12.     public List<Cost> findAll() throws DataAccessException {  
  13.         String sql = " from Cost";  
  14.         List<Cost> list = super.getHibernateTemplate().find(sql);  
  15.         return list;  
  16.     }  
  17.   
  18.     @Override  
  19.     public List<Cost> findByPage(int page, int pageSize) {  
  20.         List list = (List) super.getHibernateTemplate().execute(  
  21.                 new HibernateCallback() {  
  22.   
  23.                     @Override  
  24.                     public Object doInHibernate(Session session)  
  25.                             throws HibernateException, SQLException {  
  26.                         String hql = "from Cost";  
  27.                         Query query = session.createQuery(hql);  
  28.                         int begin = (page - 1) * pageSize;  
  29.                         query.setFirstResult(begin);  
  30.                         query.setMaxResults(pageSize);  
  31.   
  32.                         return query.list();  
  33.                     }  
  34.                 });  
  35.   
  36.         return list;  
  37.     }  
  38.   
  39.     @Override  
  40.     public int findTotalPage(int pageSize) throws DataAccessException {  
  41.         String hql = "select count(*) from Cost";  
  42.         Session session = super.getSession();  
  43.         long size = (Long) session.createQuery(hql).uniqueResult();  
  44.         session.close();// 一定记得关闭session,使用getHibernateTemplate()会在调用结束后自动关闭session  
  45.         if (size % pageSize == 0) {  
  46.             return (int) (size / pageSize);  
  47.         } else {  
  48.             return (int) (size / pageSize + 1);  
  49.         }  
  50.     }  
  51.   
  52.     @Override  
  53.     public void deleteById(Integer id) throws DataAccessException {  
  54.         Cost cost = findById(id);  
  55.         super.getHibernateTemplate().delete(cost);  
  56.     }  
  57.   
  58.     @Override  
  59.     public Cost findByName(String feeName) throws DataAccessException {  
  60.         String sql = "from Cost where NAME=?";  
  61.         Object[] params = { feeName };  
  62.         List<Cost> cost = super.getHibernateTemplate().find(sql, params);  
  63.         if (cost.isEmpty()) {  
  64.             return null;  
  65.         }  
  66.         return cost.get(0);  
  67.     }  
  68.   
  69.     @Override  
  70.     public Cost findById(Integer id) throws DataAccessException {  
  71.         Cost cost = (Cost) super.getHibernateTemplate().load(Cost.class, id);  
  72.         return cost;  
  73.     }  
  74.   
  75.     @Override  
  76.     public void updateCost(Cost cost) throws DataAccessException {  
  77.         super.getHibernateTemplate().update(cost);  
  78.     }  
  79.   
  80. }  

  d.将DAO实现类扫描到Spring容器

  e.在Spring配置中,定义SessionFactory对象,给DAO注入。

[html]  view plain  copy
  1.        <!-- 开启组件扫描 -->  
  2. <context:component-scan base-package="com.test"></context:component-scan>  
  3.   
  4. <!-- 定义一个连接池对象dataSource -->  
  5. <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource">  
  6.     <property name="username" value="system"></property>  
  7.     <property name="password" value="123456"></property>  
  8.     <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>  
  9.     <property name="url" value="jdbc:oracle:thin:@localhost:1521:test"></property>  
  10.     <property name="maxActive" value="20"></property><!-- 最大连接数 -->  
  11.     <property name="initialSize" value="1"></property><!-- 初始连接数 -->  
  12. </bean>  
  13.   
  14. <!-- 定义SessionFactory组件,给DAO注入 -->  
  15. <bean id="sessionFactory"  
  16.     class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  17.     <!--注入连接池对象 -->  
  18.     <property name="dataSource" ref="myDataSource"></property>  
  19.     <!-- 注入Hibernate 框架参数 -->  
  20.     <property name="hibernateProperties">  
  21.         <props>  
  22.             <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>  
  23.             <prop key="hibernate.show_sql">true</prop>  
  24.             <prop key="hibernate.format_sql">true</prop>  
  25.         </props>  
  26.     </property>  
  27.     <!-- 注入映射描述文件 -->  
  28.     <property name="mappingResources">  
  29.         <list>  
  30.             <value>com/test/pojo/Cost.hbm.xml</value>  
  31.         </list>  
  32.     </property>  
  33. </bean>  

  f.测试
[java]  view plain  copy
  1. @Test  
  2. public void test1() {  
  3.     String conf = "/applicationContext.xml";  
  4.     ApplicationContext ac = new ClassPathXmlApplicationContext(conf);  
  5.   
  6.     ICostDao costDao = (ICostDao) ac.getBean("hibernateCostDAO");  
  7.     // costDao.deleteById(122);  
  8.     List<Cost> list = costDao.findAll();  
  9.     for (Cost c : list) {  
  10.         System.out.println(c.getId() + " " + c.getName());  
  11.     }  
  12. }  

PS:如果需要使用Session可以采用下面两种方法:
(1)用HibernateDaoSupport提供的getSession()方法,用完后必须关闭。
(2)使用HibernateTemplate.execute()方法,以回调方式使用session.不需要关闭,因为由HibernateTemplate统一关闭处理(推荐)

3.Spring整合Struts

    (示例见SpringTest04)


1)单独使用Struts开发的流程
  hello.action-->Struts Filter控制器-->struts.xml-->HelloAction-->hello.jsp
2)引入Spring开发框架
 引入jar包和配置

*3)采用组件扫描,将Action交给Spring管理

applicationContext.xml:

[html]  view plain  copy
  1. <!-- 开启组件扫描 -->  
  2. <context:component-scan base-package="com.test"></context:component-scan>  

*4)引入struts2-spring-plugin.jar开发包【原理见下文4】
  (struts2利用该插件去spring容器获取Action对象,处理请求)

*5)修改原有<action>配置,将class属性指定成Spring中Action对象的id值

[java]  view plain  copy
  1. @Service  
  2. @Scope("prototype")  
  3. public class HelloAction {  
  4.     private String msg;  
  5.     @Resource  
  6.     private MessageDao dao;  
  7.   
  8.     public String execute() {  
  9.         msg = dao.getMessage();  
  10.         System.out.println("执行Action...");  
  11.         return "success";  
  12.     }  
  13.   
  14.     //省略get/setMsg();  
  15. }  
[java]  view plain  copy
  1. //交由StrutsSpringObjectFactory创建  
  2. //将Spring容器中id名与setxxx一致的Bean对象注入  
  3. public class HelloAction1 {  
  4.     private String msg;  
  5.     private MessageDao dao;  
  6.   
  7.     // StrutsSpringObject将Spring容器中id名与setxxx一致的Bean对象注入  
  8.     public void setJdbcMessageDao(MessageDao dao) {  
  9.         this.dao = dao;  
  10.     }  
  11.   
  12.     public String execute() {  
  13.         msg = dao.getMessage();  
  14.         return "success";  
  15.     }  
  16.   
  17.     //省略get/setMsg();  
  18. }  
[java]  view plain  copy
  1. public interface MessageDao {  
  2.     public String getMessage();  
  3. }  
[java]  view plain  copy
  1. @Repository//配置注解后默认id=jdbcMessageDao  
  2. public class JdbcMessageDao implements MessageDao {  
  3.     public String getMessage() {  
  4.         // 访问数据库,获取出信息  
  5.         System.out.println("访问数据库,获取出信息");  
  6.         return "新年快乐";  
  7.     }  
  8. }  
struts.xml:
[html]  view plain  copy
  1. <struts>  
  2.     <!-- http://localshost:8080/struts01a/NAMESPACE/ACTIONNAME.action -->  
  3.     <!-- 记忆口诀: URL虽然长,namespace站中央; action name排队尾,action后缀不要忘; extends包继承,action   
  4.         class做封装; action method找方法,返回值让result忙 -->  
  5.     <package name="demo1" namespace="/day01" extends="struts-default">  
  6.         <!-- struts2-spring-plugin.jar利用helloAction 当做id去Spring容器寻找Bean对象 -->  
  7.         <!-- 走StrutsSpringObjectFactory的try流程,整合方法一(参考4中原理分析图ssh-1.jpg) -->  
  8.         <action name="hello" class="helloAction" method="execute">  
  9.             <result>/hello.jsp</result>  
  10.         </action>  
  11.         <!-- 走StrutsSpringObjectFactory的catch流程,整合方法二(参考4中原理分析图ssh-2.jpg),此时生成的Action在容器外 -->  
  12.         <action name="hello1" class="com.test.action.HelloAction1"  
  13.             method="execute">  
  14.             <result>/hello.jsp</result>  
  15.         </action>  
  16.     </package>  
  17. </struts>  
hello.jsp:

[html]  view plain  copy
  1. <html>  
  2. <head>  
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
  4. <title>Insert title here</title>  
  5. </head>  
  6. <body>  
  7.     信息:  
  8.     <br />${msg }  
  9. </body>  
  10. </html>  
index.jsp:

[html]  view plain  copy
  1. <html>  
  2. <head>  
  3. </head>  
  4. <body>  
  5.     <a href="day01/hello.action">Struts+Spring整合案例1</a><!--走try逻辑,见下文4原理分析 -->  
  6.     <a href="day01/hello1.action">Struts+Spring整合案例2</a><!-- 走catch逻辑,见下文4原理分析  -->  
  7.     <br>  
  8. </body>  
  9. </html>  

*6)在web.xml中定义ContextLoaderListener,用于在服务器启动时,实例化Spring容器,在web.xml中采用<content-param>指定Spring。

web.xml:

[html]  view plain  copy
  1.        <filter>  
  2.     <filter-name>Struts2</filter-name>  
  3.     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  4. </filter>  
  5.   
  6. <filter-mapping>  
  7.     <filter-name>Struts2</filter-name>  
  8.     <url-pattern>/*</url-pattern>  
  9. </filter-mapping>  
  10.   
  11. <!-- 指定Spring配置位置 -->  
  12.  <context-param>  
  13.     <param-name>contextConfigLocation</param-name>  
  14.     <param-value>classpath:applicationContext.xml</param-value>  
  15.  </context-param>  
  16.    
  17. <!-- 封装了实例化Spring容器功能 -->  
  18.  <listener>  
  19.     <listener-class>  
  20.     org.springframework.web.context.ContextLoaderListener  
  21.     </listener-class>  
  22.  </listener>  
  23.   
  24. <welcome-file-list>  
  25.     <welcome-file>index.jsp</welcome-file>  
  26. </welcome-file-list></span>  

7)测试

点击任何链接都可看到相同效果:



PS:整合后的流程如下
  hello.action-->Struts Filter控制器-->struts.xml-->struts2-spring-plugin.jar-->Spring容器获取Action对象(可以注入dao)-->hello.jsp

4.struts2-spring-plugin.jar原理

  在Struts2底层有一个StrutsObjectFactory组件,用于实例化Struts2中的Action等组件对象。当引入了struts2-spring-plugin之后,该插件提供了一个StrutsSpringObjectFactory组件,它也属于ObjectFactory组件。在struts2-spring-plugin配置(struts-plugin.xml)中将原来Struts2的ObjectFactory指定成了StrutsSpringObjectFactory。因此Struts再接收请求后,会利用StrutsSpringObjectFactory获取Action对象。

struts-plugin.xml核心代码:

[html]  view plain  copy
  1. <struts>  
  2.     <bean type="com.opensymphony.xwork2.ObjectFactory" name="spring" class="org.apache.struts2.spring.StrutsSpringObjectFactory"/>  
  3.       
  4.     <!--  Make the Spring object factory the automatic default -->  
  5.     <constant name="struts.objectFactory" value="spring" />  
  6.     ...  
  7.   
  8. </struts>  
而在StrutsSpringObjectFactory中提供一个获取Action对象的方法,该方法主要逻辑如下:
[java]  view plain  copy
  1. public class StrutsSpringObjectFactory{  
  2.    //用于获取Action对象  
  3.    public Object buildAction(){  
  4.    try{  
  5.          //ssh-1.jpg整合流程1  
  6.          //获取web.xml中listener创建的Spring容器对象  
  7.     ApplicationContext ac = ...;  
  8.     //调用ac.getBean()获取Spring容器的Bean对象。用<action>配置中的class属性值去寻找  
  9.     Object action = ac.getBean(class属性值)  
  10.     //将返回的action对象交给Struts框架处理请求  
  11.          return obj;  
  12.     }catch(Exception ex){  
  13.       //ssh-2.jpg整合流程2  
  14.       //如果找不到class名字的Bean对象,会首先利用反射技术创建一个Action对象(在Spring容器外)  
  15.       Class c =  Class.forName(class属性值);  
  16.       Object obj = c.newInstance();  
  17.       //访问Spring容器,将Spring容器中id名和Action对象属性名一致的Bean对象,给Action对象注入  
  18.       //返回Action对象给Struts框架处理请求  
  19.     }  
  20.    }  
  21. }  
综上,由于struts2-spring-plugin插件中StrutsSpringObjectFactory的buildAction的try...catch...流程,导致Struts和Spring有两种整合方
法和流程。参考下图ssh1.jpg和ssh2.jpg

ssh1.jpg:


ssh2.jpg:


PS:选择哪种整合方法?
  一般如果有明确的Action、Service、DAO组件分类,建议使用ssh2.jpg整合流程;
  如果没有封装Service组件,采用Action直接调用DAO的方式,则建议使用ssh1.jsp,将Action放入容器内;
  若需采用AOP切入事务管理,因为AOP只能将容器内的Bean作为目标对象,故不能将Action分离到容器外

5.SSH处理流程

  1)启动服务器时,加载web.xml,将Spring容器和Struts控制器实例化
  2)客户端发出URL请求,请求进入Struts控制处理器
  3)Struts控制器如果发现是/login.action或/login格式请求,会进入Action组件的处理流程。Struts控制器根据struts.xml中<action>配置寻找Action对象。
  4)Struts控制器调用struts-spring-plugin.jar开发包提供的ObjectFactory组件获取Action对象。有以下两种获取方法:
    a.会利用<action>配置的class属性当id去Spring容器中寻找。
    b.会根据<action>配置的class属性利用反射机制生成一个Action对象。然后可以将Spring容器中Bean对象给Action对象属性注入(容器中Bean对象的id=Action对象,可以使用@Resource注解按类型注入)
  5)Struts控制器执行Action对象execute()方法处理请求。(DAO等组件以注入的方式使用)
  6)Struts控制器根据execute()方法返回值调用Result组件,生成响应信息
  7)给客户端响应输出
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值