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