您现在的位置是:蓝石榴 > 个人博客 > OSGI

个人博客

OSGi原理与最佳实践--Spring-DM的Web应用

2014-09-11OSGI 6455
这里,来看一下Web版的HelloWorld。这里主要是想介绍在Spring-DM中的另外两个Bundle,一个是org.springframework.osgi.web,另外一个是org.springframework.osgi.web.extender。
1.简介

这里,来看一下Web版的HelloWorld。这里主要是想介绍在Spring-DM中的另外两个Bundle,一个是org.springframework.osgi.web,另外一个是org.springframework.osgi.web.extender。大家还记得,在Spring-DM的例子中,我们用到了org.springframework.osgi.extender 这个Bundle。这里的org.springframework.osgi.web.extender 这个Bundle是用在Web环境中的一个Extender。

其实构造Web版的HelloWorld有多种方法。一种方式是可以通过嵌入HttpServer来完成一个Web应用。而这里不采用这样的方案,我们采用Spring-DM的WebExtender来部署一个Web程序。

在Eclipse中有两个方案来创建我们的工程:一个是创建一个标准的Web工程,这样的做法有一个不方便的地方是调试的问题;另外一个办法是创建一个插件工程,而这个工程打包后是拥有Web应用结构的jar包。下面,我们就来动手完成这个例子。

2.环境搭建

我们在完成Spring-DM的HelloWorld的时候,搭建了一个环境。现在,要在那个环境的基础上再引入几个Bundle,分别是org.springframework.osgi.catalina.osgi、org.springframework. osgi.catalina.start.osgi 、org.springframework.osgi.servlet-api.osgi 、org.springframework.osgi.web 、org.springframework.osgi.web.extender。其中后面两个Bundle是从dist目录下导入的,前面三个是从lib目录下导入的。导入这些Bundle后,我们的Eclipse看起来应该是如图1-62所示的样子。

接着,我们要修改Run Configurations,设置org.springframework.osgi.web.extender的Start Level,需要把这个Bundle的Start Level修改得比别的Bundle大。另外就是在Target Platform中要选择javax.servlet和org.apache.commons.logging这两个Bundle。如图1-63所示。

然后点击“Run”,可以在Eclipse的Console中看到类似如图1-64所示的显示。

这个时候,也可以查看到8080端口已经是在LISTEN的状态。我们的Web版环境准备结束,下面就来进行开发。

3.Web应用开发

Web应用开发步骤如下。

第一步,创建插件工程。

我们创建一个名为HelloWorldWeb的插件工程。

第二步,添加WEB-INF目录和index.html文件,并且在WEB-INF目录中加入web.xml文件。

这样,我们的工程看起来应该如图1-65所示。

第三步,引入Package(见图1-66)。

第四步,创 建HelloWorldServlet。我们在这里也要引入前面HelloWorld例子中的TimeService。

第五步,编辑index.html。

这里,我们可以随便在index.html中搞点儿什么你喜欢的。

第六步,编辑web.xml。

这个web.xml基本就是普通的Web应用中的配置,在这个web.xml中,我们加入了Spring的ApplicationContext的配置:

<context-param>

<param-name>contextClass</param-name>

<param-value>org.springframework.osgi.web.context.support.

OsgiBundleXmlWebApplicationContext</param-value>

</context-param>

第七步,添加applicationContext.xml。我们在WEB-INF目录下添加applicationContext.xml文件,这里的配置是为了引入TimeService,内容如下:

<!--引入OSGi Service的定义-->

<osgi:reference id="osgiTimeService" interface="org.osgichina.demo.timeservice.TimeService"/>

第八步,配置Run Configurations。

我们要在Run Configurations的Target Platform中加入三个Bundle,分别是javax.servlet.jsp、org.apache.jasper、org.apache.commons.el。

第九步,启动,运行。

我们会看到Console中会输入类似下面的信息:

信息: Successfully deployed bundle [HelloWorldWeb Plug-in (HelloWorldWeb)] at [/HelloWorldWeb] on server org.apache.catalina.core.StandardService/1.0

至此,可以在浏览器上测试一下我们的应用了。

打开浏览器,输入http://localhost:8080/HelloWorldWeb/。会看到如图1-67所示的显示。

然后,再输入http://localhost:8080/HelloWorldWeb/hello。将会看到如图1-68所示的内容。

好了,我们的Web应用已经可以正常工作了,并且也可以方便地在Eclipse的集成环境中调试我们的程序。

很赞哦!(1362)