Jetty實戰(2)之嵌入式執行Jetty多Connector
阿新 • • 發佈:2019-01-03
在嵌入執行Jetty的時候,有時候想要啟動兩個埠,或者通過一個Jetty server提供多個不同服務,比如說使用8080來指定預設訪問埠,使用8433指定https訪問埠等等,此時就可以通過建立多個Connector來解決。
1. 首先建立一個Server類,其中建立了兩個Connector例項,一個繫結到了8080埠,另一個繫結到了9090埠:
- 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;
- publicclass MyServer {
-
public
- 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();
- }
- }
- 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;
- publicclass HelloHandler extends AbstractHandler {
- publicvoid 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("<h1>Hello World</h1>");
- response.getWriter().println("<li>Request url: " + target + "</li>");
- response.getWriter().println("<li>Server port: " + request.getServerPort() + "</li>");
- }
- }