spring整合struts2

时间:2022-05-04
本文章向大家介绍spring整合struts2,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

spring 与struts2整合,由于struts是一个web框架,所以需要在项目中加入spring与web相关的包。其次,在web中应用spring时应该在web应用加载时就创建IOC容器(ApplicationContext),所以在web应用初始化时就创建。spring框架在web应用的ServlteContextListener的init方法中获取了Ioc容器,并将其放入ServletContext(即application)对象中,我们在使用时只需要从application中取出来就可以了。spring提供了 WebApplicationContextUtils.getWebApplicationContext(application) 方法取出ioc容器(ApplicationContext)。

所以分为以下步骤:

  1. 配置
  2. 取出Ioc容器

web.xml文件的配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

 <!-- 配置 Spring 配置文件的名称和位置 -->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
 </context-param>
 
 <!-- 启动 IOC 容器的 ServletContextListener -->
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <!-- 以上配置在非web应用中无需配置 -->
 
 <!-- 配置 Struts2 的 Filter -->
 <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>

</web-app>

获取Ioc容器并使用:

  ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(application);
  
  Person person = ctx.getBean(Person.class);
  
  person.hello();

其次,在spring配置文件中配置struts的action时,需要指定其scope属性为proptype(非单例的)

<?xml version="1.0" encoding="UTF-8"?>
<beans
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

 <bean id="person" class="com.yawn.bean.Person">
  <property name="name" value="yawn"></property>
 </bean>
 
 <bean id="personService" class="com.yawn.service.PersonService"></bean>
 
 <!-- acion 对应的bean必须为非单例的 -->
 <bean id="personAction" class="com.yawn.action.PersonAction" scope="prototype">
  <property name="personService" ref="personService"></property>
 </bean>

</beans>

最后,在struts配置文件中使用action时,就可以直接用bean的id来引用了

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
 <package name="default" namespace="/" extends="struts-default">

  <action name="personAction" class="personAction">
   <result>/success.jsp</result>
  </action>
  
 </package>
</struts>