我在這裏要講的就是如何基於equinox開發一個web bundle.(equinox是OSGI的一個實現,由於eclipse是它的一個應用而聞名)
我是用eclipse 3.51來開發的,這點有時候很重要,equinox更新速度很快,如果沒有跟着教程用同樣的版本。常常會因爲找不到jar包或者調試方式有差異而使得開發起來不那麼順暢。
準備:
只要準備好基本的JDK環境和eclipse 3.51 開發境即可。
第一步:創建工程
你選擇的是一個eclipse plugin 項目.
填好項目名稱,指定target platfrom 爲 OSGI framework
點擊兩次下一步,你的工程就建好了。
第二步:代碼實施
引入所需的bundle依賴
這裏用的是jetty 的 http 實現
寫一個selvlet
com.webex.robet.servlet.ShowMessage
package com.webex.robet.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ShowMessage extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -7035663685406738727L;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doGet(req, resp);
resp.setContentType("text/html");
ServletOutputStream output = resp.getOutputStream();
output.println("is that right?");
output.close();
return;
}
}
在 web_files 目錄 放一個html文件
然後在根目錄下plugin.xml 內容如下:
<plugin> <extension point="org.eclipse.equinox.http.registry.resources"> <resource alias="/files" base-name="/web_files" /> </extension> <extension point="org.eclipse.equinox.http.registry.servlets"> <servlet alias="/test" class="com.webex.robet.servlet.ShowMessage" /> </extension> </plugin>
第三步:查看實施情況
選項所建項目,run as -> run config, 選擇作爲 osgi 工程運行。
爲避免出現bundle 依賴問題,點選 add required bundles 按鈕, 然後點 run
是否出現如下界面?
輸入ss
出現類似上圖結果,表示你的應用已經起來了。
輸入 http://localhost/test 或 http://localhost/files/a.html 看看你的成就?
示例源碼下載:
http://dl.javaeye.com/topics/download/3c066f59-c154-3adf-9c17-f67468dadace