当前位置: 代码迷 >> 综合 >> spring和struts的集成
  详细解决方案

spring和struts的集成

热度:84   发布时间:2024-01-28 03:00:01.0

struts在使用action的时候需要spring帮助struts创建出Action对象。因为spring创建的对象,对象中的属性才会有依赖注入。要让spring创建对象,我们需要提供spring的工厂。我们可以在tomcat启动的时候把spring工厂创建出来。

servlet技术中有一个监听器技术可以监听tomcat的启动和关闭。

  1. 写监听器类。ServletContextListener

?
public class MyApplicationContextListener implements ServletContextListener {@Overridepublic void contextInitialized(ServletContextEvent sce) {
?//把spring的工厂创建出来。applicationContextSystem.out.println("tomcat启动了");}
?@Overridepublic void contextDestroyed(ServletContextEvent sce) {System.out.println("tomcat关闭了。。。");}
}
?

 

  1. 对监听器类进行配置在web.xml。

<!--配置监听器的--><listener><listener-class>com.baizhi.listener.MyApplicationContextListener</listener-class></listener>

上面是回顾了监听器的用法。实际上,spring在struts集成的时候不需要我们写监听器类。spring依赖中已经提供了监听器类。我们只需要对该监听器进行配置就可以。在创建spring工厂的时候需要指定spring配置文件的路径。

 

上面是准备工作,具体的步骤:

  1. 在web.xml指定监听器,指定spring配置文件的路径。

  2. 在web.xml指定struts的核心过滤器。

    ?<listener><!-- 配置一个监听器让tomcat启动的时候就创建出applicationContext对象 --><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 告知监听器spring配置文件的路径 --><context-param><!--这个param-name是固定的,它是ContextLoaderListener类中的属性--><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param>
    <!--struts的核心控制器--><filter><filter-name>Struts2Filter</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class></filter><filter-mapping><filter-name>Struts2Filter</filter-name><url-pattern>/*</url-pattern></filter-mapping>

     

  3. 写action类。StudentAction,action类中不需要再new业务类对象了。

    ?
    public class StudentAction {private StudentService ss;private List<Student> stuList;public String selectAll(){stuList=ss.selectAll();return "success";}
    ?public List<Student> getStuList() {return stuList;}
    ?public void setStuList(List<Student> stuList) {this.stuList = stuList;}
    ?public StudentService getSs() {return ss;}
    ?public void setSs(StudentService ss) {this.ss = ss;}
    }
    ?

     

  4. 在spring配置文件中将action类配置为bean对象。action类中bean的scope值必须配置为prototype

    <!--action类因为有属性,存储浏览器端传递的数据,所以他要配置为原型模式--><bean id="sa" class="com.baizhi.action.StudentAction" scope="prototype"><property name="ss" ref="ss"/></bean>

     

  5. 写struts的配置文件。Struts.xml

    <package name="myPack" extends="struts-default" namespace="/"><!--class的值是spring配置文件中bean的id值--><action name="student_*" class="sa" method="{1}"><result name="success">/showAll.jsp</result></action></package>
  相关解决方案