Jetty: how to programmatically configure multiple virtual hosts?

I have the following simple embedded Jetty 9 server:

    final Server server = new Server();
    final ServerConnector connector = new ServerConnector(server);
    server.setConnectors(new Connector[] { connector });
    server.setHandler(new FooBarHandler());


Requests for and are processed by this code. I want to change it so that:

  • requests go to FooBarHandler
  • requests go to BazBarHandler
  • All this configuration should be programmatically and not config files.

I am familiar with " running multiple instances of java set-top boxes with the same port (80) " and but can't seem to look right programmatically.


source to share

1 answer

First of all, just like in xml configuration, the virtualHost property is within org.eclipse.jetty.server.handler.ContextHandler.setVirtualHosts(String[] vhosts)

. So my guest is an easy way:

ContextHandler fooContextHandler = new ContextHandler("/");
fooContextHandler.setVirtualHosts(new String[]{"foo"});
fooContextHandler.setHandler(new FooBarHandler());

ContextHandler bazContextHandler = new ContextHandler("/");
bazContextHandler.setVirtualHosts(new String[]{"baz"});
bazContextHandler.setHandler(new BazBarHandler());

HandlerCollection handler = new HandlerCollection();





All Articles