I wrote a contexthandler to map http://hostname:9001/gm/test
as follow:
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();
}
but it doesn't work. If I remove var contextHandler in up codes. request http://localhost:9001/test
it work. invoked Testhandle.doHandle(). if I want add parent context path to all contextHandlers in ContextHandlerCollection, how to do it ?
A nested ContextHandlerCollection
is not a context of its own, and are not additive to parent contexts.
A Handler only knows about itself and below, not what is above it.
Your code essentially says the following
Server
+ HandlerCollection
+ ContextHandler "/gm"
| + ContextHandlerCollection
| + TestHandler "/test"
+ DefaultHandler
If the incoming request is on http://localhost:9001/gm/test
then the processing of that request will hit the ContextHandler "/gm"
and allow that sub-tree to be processed (as it matches the incoming request). Then it hits the TestHandler "/test"
(Which I'm assuming does its own context path or target logic), and then doesn't match anymore as /gm/test != /test
as the TestHandler knows nothing about the ContextHandler above it.
Your code could look like this ...
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();
}