Struts2与Spring整合后,可以使用Spring的配置文件applicationContext.xml来描述依赖关系,在Struts2的配置文件struts.xml来使用Spring创建的bean。
1.导入jar包
2.配置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">
<display-name>spring-6</display-name>
<!-- 配置 Spring 配置文件的名称和位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:Application.xml</param-value>
</context-param>
<!-- 启动 IOC 容器的 ServletContextListener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置 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>
3.在src下添加 struts2的配置文件
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="Personsave" class="personAction">
<result>/success.jsp</result>
</action>
</package>
</struts>
4.添加Spring bean文件Application.xml以及与struts2.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 id="person"
class="com.atguigu.spring.struts2.beans.Person">
<property name="username" value="spring"></property>
</bean>
<bean id="personService"
class="com.atguigu.spring.struts2.services.PersonService"></bean>
<!-- 注意: 在 IOC 容器中配置 Struts2 的 Action 时, 需要配置 scope 属性, 其值必须为 prototype -->
<bean id="personAction"
class="com.atguigu.spring.struts2.actions.PersonAction"
scope="prototype">
<property name="personService" ref="personService"></property>
</bean>
</beans>
5.测试环境是否搭建成功,建立beans类,action类
bean类
public class Person {
private String username;
public void setUsername(String username) {
this.username = username;
}
action类
public void hello(){
System.out.println("my name is "+username);
}
public class PersonAction {
public String execute(){
return "success";
}
}
6.在WebContent建立index.jsp,success.jsp
index.jsp
<a href="Personsave">test</a>
点击“test”,将跳转到success.jsp.整合成功