OSGI開發web應用
開發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
可以得到如下頁面,表示執行成功。