下面列出了org.eclipse.jetty.server.Server#setHandler ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void main( String[] args ) throws Exception {
Server server = new Server(8080);
// Create the 'root' Spring application context
final ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.addEventListener(new ContextLoaderListener());
context.setInitParameter("contextClass",AnnotationConfigWebApplicationContext.class.getName());
context.setInitParameter("contextConfigLocation",AppConfig.class.getName());
// Create default servlet (servlet api required)
// The name of DefaultServlet should be set to 'defualt'.
final ServletHolder defaultHolder = new ServletHolder( "default", DefaultServlet.class );
defaultHolder.setInitParameter( "resourceBase", System.getProperty("user.dir") );
context.addServlet( defaultHolder, "/" );
server.setHandler(context);
WebSocketServerContainerInitializer.configureContext(context);
server.start();
server.join();
}
@Before
public void startJetty() throws Exception {
Tracee.getBackend().clear();
server = new Server(new InetSocketAddress("127.0.0.1", 0));
ServletContextHandler context = new ServletContextHandler(null, "/", ServletContextHandler.NO_SECURITY);
final DispatcherServlet dispatcherServlet = new DispatcherServlet();
dispatcherServlet.setContextClass(AnnotationConfigWebApplicationContext.class);
dispatcherServlet.setContextInitializerClasses(TraceeInterceptorSpringApplicationInitializer.class.getCanonicalName());
dispatcherServlet.setContextConfigLocation(TraceeInterceptorSpringConfig.class.getName());
context.addServlet(new ServletHolder(dispatcherServlet), "/");
server.setHandler(context);
server.start();
ENDPOINT_URL = "http://" + server.getConnectors()[0].getName() + "/";
}
public EngineWebServer(final int port)
{
// Configure Jetty to use java.util.logging, and don't announce that it's doing that
System.setProperty("org.eclipse.jetty.util.log.announce", "false");
System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.JavaUtilLog");
server = new Server(port);
final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);
// Our servlets
context.addServlet(MainServlet.class, "/main/*");
context.addServlet(DisconnectedServlet.class, "/disconnected/*");
context.addServlet(GroupsServlet.class, "/groups/*");
context.addServlet(GroupServlet.class, "/group/*");
context.addServlet(ChannelServlet.class, "/channel/*");
context.addServlet(RestartServlet.class, "/restart/*");
context.addServlet(StopServlet.class, "/stop/*");
// Serve static files from webroot to "/"
context.setContextPath("/");
context.setResourceBase(EngineWebServer.class.getResource("/webroot").toExternalForm());
context.addServlet(DefaultServlet.class, "/");
server.setHandler(context);
}
@BeforeClass
public static void setUp() throws Exception {
// Check if executed inside target directory or module directory
String pathPrefix =new File(".").getCanonicalFile().getName().equals("target") ? "../" : "./";
server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(18080);
connector.setHost("localhost");
server.setConnectors(new Connector[]{connector});
WebAppContext context = new WebAppContext();
context.setDescriptor(pathPrefix + "src/main/webapp/WEB-INF/web.xml");
context.setResourceBase(pathPrefix + "src/main/webapp");
context.setContextPath("/");
context.setParentLoaderPriority(true);
server.setHandler(context);
server.start();
client = ClientBuilder.newClient();
root = client.target("http://" + connector.getHost() + ':' + connector.getPort() + '/');
}
private static Server startHttp1() throws Exception {
final Server server = new Server(0);
final ServletHandler handler = new ServletHandler();
handler.addServletWithMapping(newServletHolder(thriftServlet), TSERVLET_PATH);
handler.addServletWithMapping(newServletHolder(rootServlet), "/");
handler.addFilterWithMapping(new FilterHolder(new ConnectionCloseFilter()), "/*",
EnumSet.of(DispatcherType.REQUEST));
server.setHandler(handler);
for (Connector c : server.getConnectors()) {
for (ConnectionFactory f : c.getConnectionFactories()) {
for (String p : f.getProtocols()) {
if (p.startsWith("h2c")) {
fail("Attempted to create a Jetty server without HTTP/2 support, but failed: " +
f.getProtocols());
}
}
}
}
server.start();
return server;
}
public static Server initServer() {
Profiles.setProfileAsSystemProperty(Profiles.DEVELOPMENT);
WebAppContext webAppContext = new WebAppContext();
Server server = new Server(PORT);
server.setHandler(webAppContext);
return server;
}
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
ServletContextHandler handler = new ServletContextHandler();
handler.setContextPath("/");
handler.setInitParameter("contextConfigLocation", "classpath*:spring-mvc.xml");
ServletHolder servletHolder = new ServletHolder();
servletHolder.setInitOrder(1);
servletHolder.setHeldClass(DispatcherServlet.class);
servletHolder.setInitParameter("contextConfigLocation", "classpath*:spring-mvc.xml");
handler.addServlet(servletHolder, "/");
server.setHandler(handler);
server.start();
server.join();
}
/**
* starts the web server
*
* @throws Exception in case of an unexpected exception
*/
public static void startWebSocketServer() throws Exception {
Configuration conf = Configuration.getConfiguration();
if (!conf.has("http_port")) {
return;
}
Server server = new Server();
String host = conf.get("http_host", "localhost");
int port = -1;
if (conf.has("http_port")) {
port = conf.getInt("http_port", 8080);
ServerConnector connector = new ServerConnector(server);
connector.setHost(host);
connector.setPort(port);
// TODO connector.setForwarded(Boolean.parseBoolean(conf.get("http_forwarded", "false")));
server.addConnector(connector);
}
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
server.setHandler(context);
ServletHolder holderEvents = new ServletHolder("ws", MarauroaWebSocketServlet.class);
context.addServlet(holderEvents, "/ws/*");
context.addServlet(new ServletHolder(new WebServletForStaticContent(marauroad.getMarauroa().getRPServerManager())), "/*");
server.start();
}
/**
* Creates a server which delegates the request handling to a web
* application.
*
* @return a server
*/
public static Server createWebAppServer() {
// Adds an handler to a server and returns it.
Server server = createBaseServer();
String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath();
Handler webAppHandler = new WebAppContext(webAppFolderPath, APP_PATH);
server.setHandler(webAppHandler);
return server;
}
/**
* init and start a jetty server, remember to call server.stop when the task is finished
*/
protected Server startServerWithHandlers(ContextHandler... handlers) throws Exception {
server = new Server(PORT);
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(handlers);
server.setHandler(contexts);
server.start();
return server;
}
@Override
@BeforeClass
protected void setup() throws Exception {
internalSetup();
backingServer1 = new Server(0);
backingServer1.setHandler(newHandler("server1"));
backingServer1.start();
backingServer2 = new Server(0);
backingServer2.setHandler(newHandler("server2"));
backingServer2.start();
}
@BeforeEach
void setUp() throws Exception {
server = new Server();
Path keyStorePath = Paths.get(ReporterFactoryTest.class.getResource("/keystore").toURI());
final SslContextFactory sslContextFactory = new SslContextFactory(keyStorePath.toAbsolutePath().toString());
sslContextFactory.setKeyStorePassword("password");
sslContextFactory.getSslContext();
final HttpConfiguration httpConfiguration = new HttpConfiguration();
httpConfiguration.setSecureScheme("https");
httpConfiguration.setSecurePort(0);
final HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration);
httpsConfiguration.addCustomizer(new SecureRequestCustomizer());
final ServerConnector httpsConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(httpsConfiguration));
httpsConnector.setPort(0);
server.addConnector(httpsConnector);
server.setHandler(new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) {
baseRequest.setHandled(true);
requestHandled.set(true);
}
});
server.start();
configuration = SpyConfiguration.createSpyConfig();
reporterConfiguration = configuration.getConfig(ReporterConfiguration.class);
when(reporterConfiguration.getServerUrls()).thenReturn(Collections.singletonList(new URL("https://localhost:" + getPort())));
}
@Override
public void run() {
Server server = new Server(new QueuedThreadPool(maxThreads, 8, idleTimeout, queue));
ServerConnector connector = new ServerConnector(server, acceptors, selectors);
connector.setIdleTimeout(idleTimeout);
connector.setPort(port);
connector.setHost(host);
connector.setName("Continuum Ingress");
server.setConnectors(new Connector[] { connector });
HandlerList handlers = new HandlerList();
Handler cors = new CORSHandler();
handlers.addHandler(cors);
handlers.addHandler(new InfluxDBHandler(url, token));
server.setHandler(handlers);
JettyUtil.setSendServerVersion(server, false);
try {
server.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static TestServer createAndStartServer(AnnotationConfigWebApplicationContext applicationContext) {
int port = NEXT_PORT.incrementAndGet();
Server server = new Server(port);
try {
server.setHandler(getServletContextHandler(applicationContext));
server.start();
} catch (Exception e) {
LOGGER.error("Error starting server", e);
}
return new TestServer(server, applicationContext, port);
}
public AuthTestMockServer(int port) {
this.port = port;
server = new Server(this.port);
ServletHandler handler = new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping(AuthTestMockEndpoint.class, "/*");
}
public static Server initServer() {
Profiles.setProfileAsSystemProperty(Profiles.DEVELOPMENT);
WebAppContext webAppContext = new WebAppContext();
Server server = new Server(PORT);
server.setHandler(webAppContext);
return server;
}
/**
* Prepares a webapp hosting environment to get {@link ServletContext} implementation
* that we need for testing.
*/
protected ServletContext createWebServer() throws Exception {
QueuedThreadPool qtp = new QueuedThreadPool();
qtp.setName("Jetty (HudsonTestCase)");
server = new Server(qtp);
explodedWarDir = WarExploder.getExplodedDir();
WebAppContext context = new WebAppContext(explodedWarDir.getPath(), contextPath);
context.setResourceBase(explodedWarDir.getPath());
context.setClassLoader(getClass().getClassLoader());
context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
context.addBean(new NoListenerConfiguration(context));
server.setHandler(context);
context.setMimeTypes(MIME_TYPES);
context.getSecurityHandler().setLoginService(configureUserRealm());
ServerConnector connector = new ServerConnector(server);
HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
// use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
config.setRequestHeaderSize(12 * 1024);
connector.setHost("localhost");
server.addConnector(connector);
server.start();
localPort = connector.getLocalPort();
return context.getServletContext();
}
public void start() throws Exception {
// Create a simple embedded jetty server on a given port
server = new Server(port);
// Define a raw servlet that does nothing but sleep for a configured
// number of seconds so we get a read timeout from the client
ServletHandler handler = new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping(SimpleServlet.class, "/*");
// start our jetty server
server.start();
}
public static void main(String[] args) throws Exception {
int port = 8080;
logger.info("Starting at http://127.0.0.1:" + port);
AccountServer accountServer = new AccountServerImpl();
createMBean(accountServer);
Server server = new Server(port);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.addServlet(new ServletHolder(new AdminPageServlet(accountServer)), AdminPageServlet.PAGE_URL);
ResourceHandler resource_handler = new ResourceHandler();
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{resource_handler, context});
server.setHandler(handlers);
server.start();
logger.info("Server started");
server.join();
}
protected static void startJetty() throws Exception {
server = new Server(PORT);
WebAppContext context = new WebAppContext();
context.setDescriptor("../server/src/main/webapp/WEB-INF/web.xml");
context.setResourceBase("../server/src/main/webapp");
context.setContextPath("/kylin");
context.setParentLoaderPriority(true);
server.setHandler(context);
server.start();
}