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);
    connector.setPort(443);
    server.setConnectors(new Connector[] { connector });
    server.setHandler(new FooBarHandler());
    server.start();
    server.join();

      

Requests for https://foo.bar.com/ and https://baz.bar.com/ are processed by this code. I want to change it so that:

  • Foo.bar.com requests go to FooBarHandler
  • Baz.bar.com 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 http://wiki.eclipse.org/Jetty/Howto/Configure_Virtual_Hosts#Configuring_Virtual_Hosts but can't seem to look right programmatically.

+3


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();
handler.addHandler(fooContextHandler);
handler.addHandler(bazContextHandler);

server.setHandler(handler);

      

+2


source







All Articles