Spring如何整合Struts2?
1.Spring整合的目标就是让IOC容器来管理Struts2的Action
2.如何整合?
A:首先加入Struts2的jar包在web.xml容器中配置Struts2的核心配置文件
<!-- 加入Struts2的核心 -->
<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>
B:在Spring的IOC容器中配置Struts2的Action(因为每次请求都创建一个新的Action所以Action是非单例模式需要在配置scope="prototype")
<bean id="personService" class="com.spring.service.PersonService"></bean>
<!-- 配置Struts2的实例 -->
<bean id="personAction" class="com.spring.action.PersonAction" scope="prototype">
<property name="personService" ref="personService"></property>
</bean>
Struts2的Action
public class PersonAction {
private PersonService personService;
public void setPersonService(PersonService personService) {
this.personService = personService;
}
public String execute() {
personService.save();
System.out.println("execute.....");
return "success";
}
}
PersonService(在SepringIoc容器管理)
public class PersonService {
public void save(){
System.out.println("PersonService.s......save ");
}
}
C:需要配置Struts2的配置文件
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<!-- spring整合 class指向springIoc容器的id-->
<action name="person-save" class="personAction">
<result>/success.jsp</result>
</action>
</package>
</struts>
class属性如果配置全类名(bean)就是struts2自己创建的因此需要在spring的IOC容器获取bean需要注意的不需要配置全类名(class属性指向Spring的IOC容器的该bean的id属性)
以上完成之需要加入整合的jar(struts2-spring-plugin-2.3.15.3.jar)
编写一个index.jsp页面
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="<%=request.getContextPath() %>/person-save">Person save</a>
</body>
</html>
启动Tomcat服务器:http://localhost:8080/spring7/index.jsp
会在控制台输出PersonService.s......save
execute.....标识成功整合Struts2