Sometimes you want to start two ports, or you can provide several different services through a jetty server, such as using 8080来 to specify the default access port, using 8433 to specify the HTTPS access port, and so on, it is possible to create multiple connector to resolve this.
1. First create a server class, where two connector instances are created, one is bound to 8080 ports, and the other is bound to 9090 ports:
[Java]View Plaincopy
- Package com.google.code.garbagecan.jettystudy.sample2;
- Import Org.eclipse.jetty.server.Connector;
- Import Org.eclipse.jetty.server.Server;
- Import Org.eclipse.jetty.server.nio.SelectChannelConnector;
- public class MyServer {
- public static void Main (string[] args) throws Exception {
- Server server = new server ();
- Selectchannelconnector Connector1 = new Selectchannelconnector ();
- Connector1.setport (8080);
- Selectchannelconnector Connector2 = new Selectchannelconnector ();
- Connector2.setport (9090);
- Server.setconnectors (new connector[] {connector1, connector2});
- Server.sethandler (New Hellohandler ());
- Server.start ();
- Server.join ();
- }
- }
2. Create a handler class that uses requests to process all clients
[Java]View Plaincopy
- Package com.google.code.garbagecan.jettystudy.sample2;
- Import java.io.IOException;
- Import javax.servlet.ServletException;
- Import Javax.servlet.http.HttpServletRequest;
- Import Javax.servlet.http.HttpServletResponse;
- Import Org.eclipse.jetty.server.Request;
- Import Org.eclipse.jetty.server.handler.AbstractHandler;
- public class Hellohandler extends Abstracthandler {
- public void handle (String target, request baserequest, HttpServletRequest request, httpservletresponse response)
- Throws IOException, Servletexception {
- Response.setcontenttype ("Text/html;charset=utf-8");
- Response.setstatus (HTTPSERVLETRESPONSE.SC_OK);
- Baserequest.sethandled (TRUE);
- Response.getwriter (). println ("
- Response.getwriter (). println ("<li>request URL:" + target + "</li>");
- Response.getwriter (). println ("<li>server port:" + request.getserverport () + "</li>");
- }
- }
3. Run the MyServer class to access http://localhost:8080/and http://localhost:9090/, respectively, through the browser.
Related: How Jetty works and how it compares to Tomcat
Jetty Multi-connector