1. 加入Spring的jar包,并且加入struts2的struts2-spring-plugin-2.0.14.jar包。
2. 修改web.xml文件加入
<!-- spring配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/applicationContext.xml,
/WEB-INF/classes/daoContext.xml,
/WEB-INF/classes/actionContext.xml,
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
3. 修改Struts.properties文件,告知Struts 2运行时使用Spring来创建对象(如Action等)。struts.objectFactory = spring
4.修改业务bean,针对spring的借口编程。
public interface IFriendServices {
public String[] getFriends();
}
public class FriendServices implements IfriendServices…
5.配置applicationContext.xml
<bean id="friendService" class="com.dyp.struts2.services.FriendServices"/>
<bean id ="friendAction" class ="com.dyp.struts2.action.FriendAction" scope ="prototype">
<property name ="friendService">
<ref local ="friendService"/>
</property>
</bean>
6.Action中
public class FriendAction implements Action {
//通过Spring注入
private IFriendServices friendService;
private String[] friends;
public void setFriendService(IFriendServices friendService) {
this.friendService = friendService;
}
………
7.struts.xml配置转发
<action name="Friend" class="friendAction">
<!-- 如果处理结果返回login,进入login.jsp页面 -->
<result name="login">/login.jsp</result>
<!-- 如果处理结果返回success,进入showBook.jsp页面 -->
<result name="success">/showFriend.jsp</result>
</action>
注意:这里的Action和平常不同的就是class属性,它对应于Spring所定义的bean的id,而不是它的类全名。