jetty:如何以编程方式配置多个虚拟主机?

时间:2014-09-11 21:27:39

标签: java jetty subdomain virtualhost embedded-jetty

我有以下简单的嵌入式Jetty 9服务器:

    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();

此代码处理https://foo.bar.com/https://baz.bar.com/的请求。我想改变它:

  • 请求foo.bar.com转到FooBarHandler
  • 请求baz.bar.com转到BazBarHandler
  • 所有这些配置都需要以编程方式,而不是配置文件。

我熟悉 " running multiple java jetty instances with same port (80)"和http://wiki.eclipse.org/Jetty/Howto/Configure_Virtual_Hosts#Configuring_Virtual_Hosts 但似乎无法以编程方式解决问题。

1 个答案:

答案 0 :(得分:2)

首先,与基于xml的配置一样,virtualHost属性在org.eclipse.jetty.server.handler.ContextHandler.setVirtualHosts(String[] vhosts)范围内。所以,我的客人是直截了当的方式:

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);