开发web的两种方式

基于OSGI开发B/S应用有两种方式:

1)在OSGI框架中嵌入Http服务器

2)在Servlet容器中嵌入OSGI框架

Http服务器嵌入到OSGI框架环境配置

配置运行环境,选择Run->Run Configuration,new一个环境


保留以下几个Bundle,包括javax.servlet、org.apache.commons.logging、org.eclipse.equinox.http.jetty、org.eclipse.equinox.http.servlet、org.eclipse.osgi、org.eclipse.osgi.services、org.mortbay.jetty

其它的都不选择


如果出现异常,比如


说明端口被占用,在Run Configuration中设置参数


重新运行,如果没有出现异常,则表示运行成功。

在osgi窗口输入ss,会看到如下结果


打开浏览器输入http://localhost:8080,得到结果如下:


OSGI开发web应用

在Eclipse中OSGi程序的开发是以插件工程的方式进行开发的。首先新建插件工程HelloWebOSGI


完成后选择下一步


在模板中选择Hello OSGI Bundle


选择下一步


“Basic OSGi Bundle”对话框,是模板需要输入的Bundle启动和停止时列印的消息内容,在此保留默认,点“Finish”。

在左侧的包浏览面板中可以看到OSGi工程的结构,“Plug-in Dependencies”下是OSGi插件运行需要的组件,src目录下是自动生成的源代码,simplewebosgi.Activator是 Bundle生成周期管理类,可以监听组件的启动和停止动作。与普通Java工程所不同的是向导会生成“META-INF”目录以及其下的文件 MANIFEST.MF文件,此文件会随插件的发布一起被打到jar包中,定义了Bundle的标识、版本、名称、运行环境等内容。右边是可视化的配置管 理器,在这里可以定义插件,配置插件运行所依赖的组件及需要导入的包,运行时环境,编译构建配置等。

然后在src下新建目录page,在page目录下建立hello.html,加入内容




<!DOCTYPE html PUBLIC          "-//W3C//DTD HTML 4.01 Transitional//EN"           "http://www.w3.org/TR/html4/loose.dtd"         >         
<html>
<head>
<meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" >
<title>a test page</title>
</head>
<body>Hello, This is a test page!</body>
</html>



 在工程中引入javax.servlet、javax.servlet.http、org.osgi.service.http这几个包,如下图所示


现在虽然HTML页面文件有了,包也配置好了,但是还不能通过HTTP访问相应的页面,如果现在测试运行访问​​http://localhost:8080​​服务,浏览器会提示找不到页面,我们需要将页面注册到OSGi Http服务中

修改生成的Activator类,注册加入HttpService服务,程序如下:



package           hellowebosgi;         

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpService;

public class Activator implements BundleActivator {

private ServiceReference serviceReference;
private HttpService httpService;
private static BundleContext bc;

/*
* (non-Javadoc)
*
* @see
* org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext
* )
*/
public void start(BundleContext context) throws Exception {
System.out.println("Hello World!!");
bc = context;
registerResource();
}

private void registerResource() {
try {
serviceReference = bc.getServiceReference(HttpService.class
.getName());
if (serviceReference != null) {
httpService = (HttpService) bc.getService(serviceReference);
httpService.registerResources("/demo", "page", null);
}
} catch (Exception e) {
e.printStackTrace();
}
}

/*
* (non-Javadoc)
*
* @see
* org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
System.out.println( "Goodbye World!!" );
unregisterResource();
}

private void unregisterResource() {
try {
httpService.unregister( "/demo" );
} catch (Exception e) {
e.printStackTrace();
}
}

}


 运行并加入HelloWebOSGI工程


启动后显示Hello World!,这是在工程启动的时候输出的内容,然后输入ss,可以看到所有的Bundle都已经被加载进来


打开浏览器,在浏览器中输入​​http://localhost:8080/demo/hello.html​​

可以得到如下页面,表示运行成功。