Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 to both https://foo.bar.com/ and https://baz.bar.com/ are handled by this code. I want to change it so that:

  • Requests to foo.bar.com go to FooBarHandler
  • Requests to baz.bar.com go to BazBarHandler
  • All of this config needs to be programmatically, not configuration files.

I'm familiar with "running multiple java jetty instances with same port (80)" and http://wiki.eclipse.org/Jetty/Howto/Configure_Virtual_Hosts#Configuring_Virtual_Hosts but can't seem to get it right programmatically.

like image 425
Pepster K. Avatar asked Dec 08 '25 21:12

Pepster K.


1 Answers

First of all, as in the xml-based configuration, the virtualHost property is within org.eclipse.jetty.server.handler.ContextHandler.setVirtualHosts(String[] vhosts). So, my guest is that the straightforward way is:

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);
like image 57
bleidi Avatar answered Dec 10 '25 09:12

bleidi