2014-11-05 44 views
0

我寫了一個ContextHandler中映射http://hostname:9001/gm/test如下:如何添加父上下文在碼頭

public static void main(String[] args) throws Exception { 
    Server server = new Server(new QueuedThreadPool(8, 6)); 
    ServerConnector connector = new ServerConnector(server); 
    connector.setPort(9001); 
    server.setConnectors(new Connector[] { connector }); 

    HandlerCollection handler = new HandlerCollection(); 
    ContextHandler contextHandler = new ContextHandler("/gm"); 

    ContextHandlerCollection contexts = new ContextHandlerCollection(); 
    contexts.setHandlers(new Handler[] { new TestHandler("/test") }); 
    contextHandler.setHandler(contexts); 

    handler.setHandlers(new Handler[] { contextHandler, new DefaultHandler() }); 
    server.setHandler(handler); 
    server.start(); 
    server.dumpStdErr(); 
    server.join(); 
} 

,但它不工作。如果我在代碼中刪除var contextHandler。請求http://localhost:9001/test它的工作。調用Testhandle.doHandle()。如果我想將Context上下文路徑添加到ContextHandlerCollection中的所有contextHandlers中,該怎麼做?

回答

0

一個嵌套的ContextHandlerCollection不是它自己的上下文,並且不能添加到父上下文中。

Handler只知道自己和下面的內容,而不是上面的內容。

您的代碼實際上是說下面

Server 
    + HandlerCollection 
     + ContextHandler "/gm" 
     | + ContextHandlerCollection 
     |  + TestHandler "/test" 
     + DefaultHandler 

如果傳入的請求是http://localhost:9001/gm/test那麼該請求的處理將達到ContextHandler "/gm"並允許子樹進行處理(因爲它匹配進來請求)。然後它碰到TestHandler "/test"(我假設它自己的上下文路徑或目標邏輯),然後不再與/gm/test != /test匹配,因爲TestHandler對它上面的ContextHandler一無所知。

你的代碼可能看起來像這樣...

public static void main(String[] args) throws Exception { 
    Server server = new Server(new QueuedThreadPool(8, 6)); 
    ServerConnector connector = new ServerConnector(server); 
    connector.setPort(9001); 
    server.setConnectors(new Connector[] { connector }); 

    HandlerCollection handlers = new HandlerCollection(); 
    server.setHandler(handlers); 

    ContextHandlerCollection contexts = new ContextHandlerCollection(); 

    String baseContext = "/gm"; 
    // map on "/gm/test" 
    contexts.addHandlers(new TestHandler(baseContext + "/test")); 
    // map on "/gm/foo" 
    contexts.addHandlers(new FooHandler(baseContext + "/foo")); 

    baseContext = "/odd"; 
    // map on "/odd/bar" 
    contexts.addHandlers(new BarHandler(baseContext + "/bar")); 

    handlers.setHandlers(new Handler[] { contexts, new DefaultHandler() }); 

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

謝謝您的回答! – nealons 2014-11-06 12:03:38