struts 2 spring2.5 整合
简述:spring2.5和struts2通过struts2-spring-plugin 此插件来整合
前提:
(1)struts2-spring-plugin这个插件,已经在你项目的classpaht下,并且 struts和spring必需的jar包已经在classpath下。至于jar包的冲突问题,根据自己实际项目情况,进行调整。
(2)对spring2.5和struts2有简单的了解,本文不包括整合之外的内容,比如:,本文默认你已经明白如何在web.xml中对struts2进行配置。
第一步:在web.xml中添加监听器
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
第二步:创建一个类 com.ddgrow.Test.java
此类作为struts2的action存在,此类的创建也交由spring管理
package com.ddgrow; public class Test{ private String msg;//由spring注入 public String getMsg(){ return msg; } public void setMsg(String msg){ this.msg = msg; } } public String execute(){ return "test"; }
第三步:创建一个jsp页面 ddgrow.jsp
<%@taglib uri="/struts-tags" prefix="s" %> <body> <!-- 会显示出Test.java中由spring注入的msg的值 --> <h1><s:property value="msg" /></h1> </body>
第四步:配置applicationContext.xml
由spring来管理action的创建,及属性的注入
<beans> <!-- 注意,此处的id号testAction将会在struts.xml中的class属性中引用,从而在struts.xml中不再指定具体的action类,也就是说,action的生命周期交给了spring来管理 --> <bean id="testAction" class="com.ddgrow.Test" > <property name="msg" value="thank your for visiting www.ddgrow.com" /> </bean> </beans>
第五步:配置struts.xml
<struts> <package name="default" extends="struts-default"> <!-- name:ddgrowTest是用来访问的路径名,比如 :/ddgrowTest.action或者ddgrowTest.do 根据你的具体配置调整后缀。 class:testAction,这里的testAction是在applicationContext.xml中指定的名称,action类从spring上下文获取,不需要struts2来创建 name:test result中的test是给返回结果页面的一个自定义的名称,在com.ddgrow.Test.java类的execute中的返回值就是test. --> <action name="ddgrowTest" class="testAction"> <result name="test">/ddgrow.jsp</result> </action> </package> </struts>
第六步:通过浏览器测试结果
在浏览器地址栏中录入 http://localhost:8080/your_project_name/ddgrowTest.action 来测试配置结果。
如果一切正确,将会显示出thank your for visiting www.ddgrow.com
否则,检查错误信息。
重要的一点是类包的冲突问题,基本上解决了此问题后,配置问题应该不大。
近期评论