Spring如何整合Struts2

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值