使用 Felix 和 Struts2 开发 Web 应用(转)
转载自http://www.ibm.com/developerworks/cn/web/1007_shaobing_flexosgi/index.html?ca=drs-
?
这篇文章的项目会有两个问题:
1. 报错velocity......的异常,因为缺少了velocity-tools-1.3.jar? 包。
2. 如果无法上网时解析struts.xml会报错,请修改src下的struts.xml的dtd文件的url 为
<!DOCTYPE struts PUBLIC
??????? "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
??????? "file:/D:/saber/workspace/OSGISSH/dtd/struts-2.0.dtd">
?
同时如果导入struts2-osgi-admin-bundle-2.2.3.jar ,也要修改这个包下的struts.xml的头!
?
?
?
?
将 Web Application 部署到 Tomcat 上并启动 Tomcat,然后在浏览器中输入 http://localhost:8080/webapp/osgi/admin/bundles.action, (webapp 是项目部署到 Tomcat 中的名字 ) 如果看到了类似于 图 5的 bundles 列表,说明 OSGi 环境配置成功。
在该项目中开发一个用于获取时间信息的接口,通过该接口可以获取字符串形式的时间信息。
清单 2. 获取时间服务接口代码
?
OSGi bundle 中的服务要能够被其他 bundle 使用,使用将服务发布出来。在该 bundle 的 Activator 的 start() 方法中注册该服务,可以发布这个服务。当这个 bundle 启动时,将获取本地时间发布为一个服务。服务发布的代码如清单 4 所示。
清单 4. 服务发布
?
在浏览器地址栏输入 http://localhost:8080/webapp/time/time.do,可以获得时间信息,此时的时间信息为本地时间信息,当前 TimeService 这个服务有 local time service 和 UTC time service 两个实现,调用的是 local time service 这个实现。
图 6. 获取本地时间页面显示
此时,在浏览器地址栏输入 http://localhost:8080/webapp/osgi/admin/shell.do,然后输入命令 stop 1, 将 Local time service 这个 bundle 停止掉,输入命令 ps, 可以看到 local time service 这个 bundle 的 state 已经变为 Resolved.
图 7. OSGi Shell 管理页面
在浏览器地址栏再次输入 http://localhost:8080/webapp/time/time.do 得到的结果如图 7 所示。
图 8. 获取 UTC 时间显示页面
通过上面的演示,我们可以看到 OSGi bundle 的动态部署能力。
?
在 Web Application 的 web.xml 加入 Spring 的监听器 , 配置如下:
清单 13. 配置 Spring 监听器
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <context-param> <param-name>contextClass</param-name> <param-value> org.springframework.osgi.web.context.support.OsgiBundleXmlWebApplicationContext </param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>osgibundle:/META-INF/spring/*.xml,/spring/*.xml </param-value> </context-param> <context-param> <param-name>parentContextKey</param-name> <param-value>parent-context-bean</param-value> </context-param>
?
在 OSGi bundle 中,如果需要用 Spring 来管理对象,则把 Spring 对象的配置文件放在 /META-INF/spring/ 目录下面,并以 xml 为扩展名即可。Spring 对象配置文件的写法在很多 Spring DM 的书籍或文章中都有讲解,这里不再重复。最后需要在 MANIFEST.MF 中加入如下声明用来配置 Spring 上下文和对象创建机制,create-asynchronously 的值为 true 表示可以允许异步创建对象。
清单 14. 配置 Spring 对象创建方式
Spring-Context: *;create-asynchronously:=true
?
回页首
小结
本文首先对 OSGi 和 Felix 进行了简要的介绍,然后通过一个示例详细介绍了使用 Felix 和 Struts 开发 Web 应用,演示了 OSGi 的动态部署特性。随后,讲解了 OSGi bundles 管理常用的命令操作,以及在开发过程中的几个常见的问题的解决方法。
<!-- CMA ID: 500011 --><!-- Site ID: 10 --><!-- XSLT stylesheet used to transform this file: dw-article-6.0-beta.xsl -->?
参考资料
学习
查看 OSGi 联盟和技术规范:了解更多和 OSGi 相关的内容和动向。讨论
My developerWorks 中文社区作者简介
韦景琪,东北大学软件学院学生,目前为 IBM 中国研究院供应链分析与优化研究实习生,从事业务流程建模、Web 服务、RCP 相关的研发。
邵兵, IBM 中国研究院供应链分析与优化研究组研究员,目前从事供应链流程分析与优化方面的研究与开发工作。对 Eclipse RCP 开发有深入的了解。他的邮箱是:shaobing@cn.ibm.com。
周英,就职于 IBM 中国研究院,目前从事绿色数据中心的研究工作,关注传感器网络与虚拟化技术。
<!-- MAIN_COLUMN_CONTENT_END --><!-- INLINE_COMMENTS_START -->建议