jetty server 9.1 multiple embeded ports and applic

2019-09-02 14:14发布

问题:

I should use one Server object, and need to open multiple ports and multiple application(WAR files). Ex, one server object, 8080 addition.war 8081 subraction.war etc.

I'm using Jetty server 9.1.0 How can I do this?

回答1:

To accomplish this, you need:

  1. Each ServerConnector should have a unique name declared via ServerConnector.setName(String)
  2. When you define your WebAppContext, declare a set of virtual hosts that take a named virtual host syntax "@{name}", where the {name} is the same one you chose for the connector. (Note: A virtualhost without the "@" sign is a traditional virtualhost based on hostnames)

Like this ...

package jetty.demo;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.webapp.WebAppContext;

public class ConnectorSpecificContexts
{
    public static void main(String[] args)
    {
        Server server = new Server();

        ServerConnector connectorA = new ServerConnector(server);
        connectorA.setPort(8080);
        connectorA.setName("connA"); // connector name A
        ServerConnector connectorB = new ServerConnector(server);
        connectorB.setPort(9090);
        connectorB.setName("connB"); // connector name B

        server.addConnector(connectorA);
        server.addConnector(connectorB);

        // Basic handler collection
        HandlerCollection contexts = new HandlerCollection();
        server.setHandler(contexts);

        // WebApp A
        WebAppContext appA = new WebAppContext();
        appA.setContextPath("/a");
        appA.setWar("./webapps/webapp-a.war");
        appA.setVirtualHosts(new String[]{"@connA"}); // connector name A
        contexts.addHandler(appA);

        // WebApp B
        WebAppContext appB = new WebAppContext();
        appB.setContextPath("/b");
        appB.setWar("./webapps/webapp-b.war");
        appB.setVirtualHosts(new String[]{"@connB"}); // connector name B
        contexts.addHandler(appB);

        try
        {
            server.start(); // start server thread
            server.join(); // wait for server thread to end
        }
        catch (Throwable t)
        {
            t.printStackTrace(System.err);
        }
    }
}


标签: java Jetty