使用 Spring 的 ContextLoaderPlugin 为 Struts 的 ActionServlet 装载 Spring 应用程序环境。在struts-config.xml中加入以下代码:
1. Action 中,使用IOC 获得服务,配置struts-config.xml
2. Spring 配置文件中注册该动作
3. 写具有 JavaBean 属性的 Struts 动作
<plug-in
className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="classpath*:modules/**/struts-spring-conf/*.xml" />
</plug-in>1. Action 中,使用IOC 获得服务,配置struts-config.xml
<!-- 一个Action 注意其type Spring 代理类 -->
<action path="/searchSubmit"
type="org.springframework.web.struts.DelegatingActionProxy"
input="/searchEntry.do" validate="true" name="searchForm">
<forward name="success" path="/WEB-INF/pages/detail.jsp" />
<forward name="failure" path="/WEB-INF/pages/search.jsp" />
</action>2. Spring 配置文件中注册该动作
<bean id="bookService"
class="ca.nexcel.books.business.BookServiceImpl" />
<bean name="/searchSubmit"
class="ca.nexcel.books.actions.SearchSubmit">
<property name="bookService">
<ref bean="bookService" />
</property>
</bean>3. 写具有 JavaBean 属性的 Struts 动作
public class SearchSubmit extends Action {
// 一个Service属性
private BookService bookService;
// getter...
public BookService getBookService() {
return bookService;
}
// setter...
public void setBookService(BookService bookService) {
this.bookService = bookService;
}
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// 调用bookService,不需要new
Book book = getBookService().read(isbn.trim());
}
}
本文介绍如何在Struts框架中集成Spring框架,通过配置实现依赖注入,避免硬编码,提高代码灵活性。具体步骤包括使用ContextLoaderPlugin配置Spring上下文,定义Action并注入业务逻辑。
3453

被折叠的 条评论
为什么被折叠?



