2015-08-22 28 views
1

我有兩個jetty嵌入式服務器, 本地主機:9001/WebApp1和本地主機:9002/WebApp2, ,你可以看到他們在不同的端口。 我希望他們在創建服務器 時共享相同的端口是否有可能? (順便說一下,它們也是兩個獨立的jar文件)。 所以我可以做這樣的事情,而不是 本地主機:9001/WebApp1和本地主機:9001/webapp2的兩個上下文一個服務器碼頭

還是我堅持與生產WAR文件然後讓他們通過了tomcat/GlassFish服務器包含

創建過程中

服務器通常我看到這個

ContextHandler context = new ContextHandler(); 
context.setContextPath("/WebApp1"); 
context.setHandler(new WebApp1()); 
Server server = new Server(9001); 
server.setHandler(context); 
server.start();    
server.join(); 

在第二程序,我想有一些看起來像這樣

ContextHandler context = new ContextHandler(); 
context.setContextPath("/WebApp2"); 
context.setHandler(new WebApp2()); 
Server server = getExistingServer(9001); 
server.addHandler(context); 

我看到有這樣的方法server.getHandlers();它返回一個處理程序數組如何添加新的處理程序到現有的列表,或者獲取現有的碼頭服務器運行在端口9001

+1

兩個獨立運行的應用程序不能共享的端口。但是,您也可以在Jetty中部署戰爭,但這意味着放棄嵌入式模型。 – fvu

+0

它看起來正確的做法是與戰爭文件沒有?,如果我與戰爭正確得到它我將使用Servlets而不是服務器實例和手動添加處理程序是正確的?我是java EE noob,因爲嵌入模式,所以我更喜歡看到我的程序在線運行,可能是使用tomcat/glassfish服務器。 – jyonkheel

+0

如果您想要定位的不僅僅是Jetty,還需要使用標準的WAR部署模式就是要走的路。 – fvu

回答

4

Jetty是一個標準的servlet容器,當然可以處理不同的上下文。 請參閱Jetty文檔第24章中的Embedding Contexts節。

這裏是ManyContexts example(碼頭文檔的一部分):

public class ManyContexts 
{ 
    public static void main(String[] args) throws Exception 
    { 
    Server server = new Server(8080); 

    ContextHandler context = new ContextHandler("/"); 
    context.setContextPath("/"); 
    context.setHandler(new HelloHandler("Root Hello")); 

    ContextHandler contextFR = new ContextHandler("/fr"); 
    contextFR.setHandler(new HelloHandler("Bonjoir")); 

    ContextHandler contextIT = new ContextHandler("/it"); 
    contextIT.setHandler(new HelloHandler("Bongiorno")); 

    ContextHandler contextV = new ContextHandler("/"); 
    contextV.setVirtualHosts(new String[] { "127.0.0.2" }); 
    contextV.setHandler(new HelloHandler("Virtual Hello")); 

    ContextHandlerCollection contexts = new ContextHandlerCollection(); 
    contexts.setHandlers(new Handler[] { context, contextFR, contextIT, contextV }); 

    server.setHandler(contexts); 

    server.start(); 
    server.join(); 
    } 
} 
+0

這個示例代碼工作一個.jar文件,但我有兩個單獨的.jar文件,我想在同一時間運行,當我運行第二個我不能再使用相同的端口給了我一個java.net。 BindException:已經在使用的地址:bind – jyonkheel

+1

您有一個主類爲您的應用程序啓動一個嵌入式Jetty。但是你可以有幾個上下文。只要在類路徑中存在對應類的JAR文件就沒有關係。所以你有一個進程運行一個Jetty和你的兩個JAR。 – vanje

+0

哦,我看到了謝謝〜 – jyonkheel