下面列出了怎么用org.eclipse.jetty.server.handler.ResourceHandler的API类实例代码及写法,或者点击链接到github查看源代码。
public static void main (String args[]) throws Exception{
logger.info("Starting JETTY server");
Server server = new Server(8080);
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(true);
resourceHandler.setWelcomeFiles(new String[]{ "resources/html/configure.html" });
resourceHandler.setResourceBase(".");
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
resourceHandler.setWelcomeFiles(new String[]{ "resources/html/configure.html" });
resourceHandler.setResourceBase(".");
context.addServlet(new ServletHolder(new ConfigurationServlet()),"/cfg");
context.addServlet(new ServletHolder(new SaveConfigurationServlet()),"/cfg/save");
context.addServlet(new ServletHolder(new LoadConfigurationServlet()),"/cfg/load");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resourceHandler, context });
server.setHandler(handlers);
server.start();
logger.info("Configuration server started at: http://localhost:8080/cfg");
server.join();
}
/**
* Starts the web server on the default {@link #PORT}.
* The given resourceBase is used to be the ROOT directory that serves the default context.
* <p><b>Don't forget to stop the returned HttpServer after the test</b>
*
* @param resourceBase the base of resources for the default context
* @throws Exception if the test fails
*/
protected void startWebServer(final String resourceBase) throws Exception {
if (server_ != null) {
throw new IllegalStateException("startWebServer() can not be called twice");
}
final Server server = buildServer(PORT);
final WebAppContext context = new WebAppContext();
context.setContextPath("/");
context.setResourceBase(resourceBase);
final ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setResourceBase(resourceBase);
final MimeTypes mimeTypes = new MimeTypes();
mimeTypes.addMimeMapping("js", MimeType.APPLICATION_JAVASCRIPT);
resourceHandler.setMimeTypes(mimeTypes);
final HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{resourceHandler, context});
server.setHandler(handlers);
server.setHandler(resourceHandler);
tryStart(PORT, server);
server_ = server;
}
public static void main(String[] args) throws Exception {
// Embedded Jetty server
Server server = new Server(HTTP_PORT);
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setWelcomeFiles(new String[] {"index.html"});
resourceHandler.setDirectoriesListed(true);
// resource base is relative to the WORKSPACE file
resourceHandler.setResourceBase("./src/main/resources");
HandlerList handlerList = new HandlerList();
handlerList.setHandlers(
new Handler[] {resourceHandler, new GraphQlHandler(), new DefaultHandler()});
server.setHandler(handlerList);
server.start();
logger.info("Server running on port " + HTTP_PORT);
server.join();
}
public static void main(String[] args) throws Exception {
//
// This example uses Jetty as an embedded HTTP server
Server server = new Server(PORT);
//
// In Jetty, handlers are how your get called backed on a request
HttpMain main_handler = new HttpMain();
// this allows us to server our index.html and GraphIQL JS code
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(false);
resource_handler.setWelcomeFiles(new String[]{"index.html"});
resource_handler.setResourceBase("./src/main/resources/httpmain");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{resource_handler, main_handler});
server.setHandler(handlers);
server.start();
server.join();
}
private static void initServer(Properties properties) throws Exception {
Integer port = Integer.valueOf(properties.getProperty("server.port"));
String host = properties.getProperty("server.host");
Integer clientId = Integer.valueOf(properties.getProperty("client.id"));
String clientSecret = properties.getProperty("client.secret");
HandlerCollection handlers = new HandlerCollection();
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(true);
resourceHandler.setWelcomeFiles(new String[]{"index.html"});
resourceHandler.setResourceBase(Application.class.getResource("/static").getPath());
VkApiClient vk = new VkApiClient(new HttpTransportClient());
handlers.setHandlers(new Handler[]{resourceHandler, new RequestHandler(vk, clientId, clientSecret, host)});
Server server = new Server(port);
server.setHandler(handlers);
server.start();
server.join();
}
private static void initServer(Properties properties) throws Exception {
Integer port = Integer.valueOf(properties.getProperty("server.port"));
String host = properties.getProperty("server.host");
Integer clientId = Integer.valueOf(properties.getProperty("client.id"));
String clientSecret = properties.getProperty("client.secret");
HandlerCollection handlers = new HandlerCollection();
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(true);
resourceHandler.setWelcomeFiles(new String[]{"index.html"});
resourceHandler.setResourceBase(Application.class.getResource("/static").getPath());
VkApiClient vk = new VkApiClient(new HttpTransportClient());
handlers.setHandlers(new Handler[]{resourceHandler, new RequestHandler(vk, clientId, clientSecret, host)});
Server server = new Server(port);
server.setHandler(handlers);
server.start();
server.join();
}
public WebServer(int port, String resRoot){
super(port);
LOG.info("Port:{}, Resources Root:{}", port, resRoot);
ResourceHandler rh0 = new ResourceHandler();
ContextHandler context0 = new ContextHandler();
context0.setContextPath("/res/*");
context0.setResourceBase(resRoot);
context0.setHandler(rh0);
//ServletHandler context1 = new ServletHandler();
//this.setHandler(context1);
ServletContextHandler context1 = new ServletContextHandler();
context1.addServlet(TestSlaveServlet.class, "/slavesite/*");
// Create a ContextHandlerCollection and set the context handlers to it.
// This will let jetty process urls against the declared contexts in
// order to match up content.
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[] { context1, context0});
this.setHandler(contexts);
}
public void start() throws Exception {
server = new Server();
connector = new ServerConnector(server);
connector.setPort(port);
server.addConnector(connector);
server.setStopAtShutdown(true);
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setResourceBase(resourceDir);
resourceHandler.setDirectoriesListed(true);
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] {resourceHandler, new DefaultHandler()});
server.setHandler(handlers);
server.start();
}
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.addServlet(new ServletHolder(new WebSocketChatServlet()), "/chat");
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setResourceBase("public_html");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{resource_handler, context});
server.setHandler(handlers);
server.start();
System.out.println("Server started!");
server.join();
}
public static void main(String[] args) throws Exception {
URI baseUri = UriBuilder.fromUri("http://localhost").port(SERVER_PORT)
.build();
ResourceConfig config = new ResourceConfig(Calculator.class);
Server server = JettyHttpContainerFactory.createServer(baseUri, config,
false);
ContextHandler contextHandler = new ContextHandler("/rest");
contextHandler.setHandler(server.getHandler());
ProtectionDomain protectionDomain = EmbeddedServer.class
.getProtectionDomain();
URL location = protectionDomain.getCodeSource().getLocation();
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setWelcomeFiles(new String[] { "index.html" });
resourceHandler.setResourceBase(location.toExternalForm());
System.out.println(location.toExternalForm());
HandlerCollection handlerCollection = new HandlerCollection();
handlerCollection.setHandlers(new Handler[] { resourceHandler,
contextHandler, new DefaultHandler() });
server.setHandler(handlerCollection);
server.start();
server.join();
}
public static void main(String[] args) throws Exception {
AccountService accountService = new AccountService();
accountService.addNewUser(new UserProfile("admin"));
accountService.addNewUser(new UserProfile("test"));
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.addServlet(new ServletHolder(new UsersServlet(accountService)), "/api/v1/users");
context.addServlet(new ServletHolder(new SessionsServlet(accountService)), "/api/v1/sessions");
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setResourceBase("public_html");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{resource_handler, context});
Server server = new Server(8080);
server.setHandler(handlers);
server.start();
server.join();
}
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.addServlet(new ServletHolder(new WebSocketChatServlet()), "/chat");
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setResourceBase("public_html");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{resource_handler, context});
server.setHandler(handlers);
server.start();
server.join();
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.append("Use port as the first argument");
System.exit(1);
}
String portString = args[0];
int port = Integer.valueOf(portString);
System.out.append("Starting at port: ").append(portString).append('\n');
Server server = new Server(port);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.addServlet(new ServletHolder(new AdminPageServlet()), AdminPageServlet.adminPageURL);
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setResourceBase("static");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{resource_handler, context});
server.setHandler(handlers);
server.start();
server.join();
}
@Test
public void testHelloWorldExternalBindingFile() throws Exception {
Server server = new Server(0);
try {
ResourceHandler reshandler = new ResourceHandler();
reshandler.setResourceBase(getLocation("/wsdl2java_wsdl/"));
// this is the only handler we're supposed to need, so we don't need to
// 'add' it.
server.setHandler(reshandler);
server.start();
Thread.sleep(250); //give network connector a little time to spin up
int port = ((NetworkConnector)server.getConnectors()[0]).getLocalPort();
env.put(ToolConstants.CFG_WSDLURL, "http://localhost:"
+ port + "/hello_world.wsdl");
env.put(ToolConstants.CFG_BINDING, "http://localhost:"
+ port + "/remote-hello_world_binding.xsd");
processor.setContext(env);
processor.execute();
reshandler.stop();
} finally {
server.stop();
server.destroy();
}
}
protected ServletContextHandler addResourceHandler(String contextPath, Path resourceBase) {
ServletContextHandler context = new ServletContextHandler();
ResourceHandler staticResource = new ResourceHandler();
staticResource.setDirectoriesListed(true);
staticResource.setWelcomeFiles(new String[] { "index.html" });
staticResource.setResourceBase(resourceBase.toAbsolutePath().toString());
MimeTypes mimeTypes = new MimeTypes();
mimeTypes.addMimeMapping("appcache", "text/cache-manifest");
staticResource.setMimeTypes(mimeTypes);
context.setContextPath(contextPath);
context.setAliasChecks(Arrays.asList(new ApproveAliases(), new AllowSymLinkAliasChecker()));
HandlerList allHandlers = new HandlerList();
allHandlers.addHandler(staticResource);
allHandlers.addHandler(context.getHandler());
context.setHandler(allHandlers);
handlers.addHandler(context);
return context;
}
@Ignore
@Test
public void testFetch() throws Exception {
String input = "12test32";
Assert.assertFalse(ForbiddenWordUtils.containsForbiddenWord(input));
ForbiddenWordUtils.setForbiddenWordFetchURL("http://localhost:10090/forbidden-test.txt");
ForbiddenWordUtils.setReloadInterval(500);
ForbiddenWordUtils.initRemoteFetch();
Server server = new Server(10090);
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(true);
resourceHandler.setBaseResource(Resource.newClassPathResource("."));
server.setHandler(resourceHandler);
server.start();
Thread.sleep(1500);
Assert.assertTrue(ForbiddenWordUtils.containsForbiddenWord(input));
server.stop();
}
private void startHttpServer() throws Exception {
KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv();
createAndConfigHttpServer(kylinConfig);
ContextHandlerCollection contexts = new ContextHandlerCollection();
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/kylin");
XmlWebApplicationContext ctx = new XmlWebApplicationContext();
ctx.setConfigLocation("classpath:applicationContext.xml");
ctx.refresh();
DispatcherServlet dispatcher = new DispatcherServlet(ctx);
context.addServlet(new ServletHolder(dispatcher), "/api/*");
ContextHandler logContext = new ContextHandler("/kylin/logs");
String logDir = getLogDir(kylinConfig);
ResourceHandler logHandler = new ResourceHandler();
logHandler.setResourceBase(logDir);
logHandler.setDirectoriesListed(true);
logContext.setHandler(logHandler);
contexts.setHandlers(new Handler[] { context, logContext });
httpServer.setHandler(contexts);
httpServer.start();
httpServer.join();
}
@Override
public void beforeAll(ExtensionContext context) {
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setBaseResource(Resource.newClassPathResource(folder));
resourceHandler.setWelcomeFiles(new String[]{"index.html"});
resourceHandler.setDirectoriesListed(true);
server = new Server(port);
HandlerList handlers = new HandlerList(resourceHandler, new DefaultHandler());
server.setHandler(handlers);
try {
server.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public TestServer(int port, File baseDirectory) {
server = new Server(port);
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setResourceBase(baseDirectory == null ? "." : baseDirectory.getAbsolutePath());
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
server.setHandler(handlers);
}
public TestServer(String protocol, String host, int port) {
server = new Server(port);
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setResourceBase(".");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
server.setHandler(handlers);
}
/**
* Creates an http server on a random port, serving the <code>dir</code>
* directory (relative to the current project).
*
* @param dir
* @throws IOException
*/
public FileServer(String dir) throws IOException {
server = new Server(0);
ResourceHandler resourceHandler = new ResourceHandler();
Path base = ProjectUtils.getProjectDirectory().resolve(dir);
resourceHandler.setResourceBase(base.toUri().toString());
resourceHandler.setDirectoriesListed(true);
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resourceHandler, new DefaultHandler() });
server.setHandler(handlers);
}
private ContextHandler createDocsWebApp(final String contextPath) {
try {
final ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(false);
// load the docs directory
final File docsDir = Paths.get("docs").toRealPath().toFile();
final Resource docsResource = Resource.newResource(docsDir);
// load the component documentation working directory
final String componentDocsDirPath = props.getProperty(NiFiProperties.COMPONENT_DOCS_DIRECTORY, "work/docs/components");
final File workingDocsDirectory = Paths.get(componentDocsDirPath).toRealPath().getParent().toFile();
final Resource workingDocsResource = Resource.newResource(workingDocsDirectory);
// load the rest documentation
final File webApiDocsDir = new File(webApiContext.getTempDirectory(), "webapp/docs");
if (!webApiDocsDir.exists()) {
final boolean made = webApiDocsDir.mkdirs();
if (!made) {
throw new RuntimeException(webApiDocsDir.getAbsolutePath() + " could not be created");
}
}
final Resource webApiDocsResource = Resource.newResource(webApiDocsDir);
// create resources for both docs locations
final ResourceCollection resources = new ResourceCollection(docsResource, workingDocsResource, webApiDocsResource);
resourceHandler.setBaseResource(resources);
// create the context handler
final ContextHandler handler = new ContextHandler(contextPath);
handler.setHandler(resourceHandler);
logger.info("Loading documents web app with context path set to " + contextPath);
return handler;
} catch (Exception ex) {
throw new IllegalStateException("Resource directory paths are malformed: " + ex.getMessage());
}
}
public static void main(String[] args) throws Exception {
//
// This example uses Jetty as an embedded HTTP server
Server server = new Server(PORT);
//
// In Jetty, handlers are how your get called back on a request
ServletContextHandler servletContextHandler = new ServletContextHandler();
servletContextHandler.setContextPath("/");
ServletHolder stockTicker = new ServletHolder("ws-stockticker", StockTickerServlet.class);
servletContextHandler.addServlet(stockTicker, "/stockticker");
// this allows us to server our index.html and GraphIQL JS code
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(false);
resource_handler.setWelcomeFiles(new String[]{"index.html"});
resource_handler.setResourceBase("./src/main/resources/httpmain");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{resource_handler, servletContextHandler});
server.setHandler(handlers);
server.start();
server.join();
}
protected synchronized void init() {
try {
buildJettyProperties();
server = new Server(new ExecutorThreadPool(HttpExcutors.getThreadPool()));
ServerConnector connector = this.createConnector();
Logs.http().info("listen port: {}", port);
String host = StartContext.httpHost();
if (host != null && host.length() > 0) {
connector.setHost(host);
}
connector.setPort(port);
server.setConnectors(new Connector[] { connector });
ServletContextHandler context = createServletContextHandler();
context.setContextPath(AppInfo.get("sumk.jetty.web.root", "/"));
context.addEventListener(new SumkLoaderListener());
addUserListener(context, Arrays.asList(ServletContextListener.class, ContextScopeListener.class));
String resourcePath = AppInfo.get("sumk.jetty.resource");
if (StringUtil.isNotEmpty(resourcePath)) {
ResourceHandler resourceHandler = JettyHandlerSupplier.resourceHandlerSupplier().get();
if (resourceHandler != null) {
resourceHandler.setResourceBase(resourcePath);
context.insertHandler(resourceHandler);
}
}
if (AppInfo.getBoolean("sumk.jetty.session.enable", false)) {
SessionHandler h = JettyHandlerSupplier.sessionHandlerSupplier().get();
if (h != null) {
context.insertHandler(h);
}
}
server.setHandler(context);
} catch (Throwable e) {
Log.printStack("sumk.http", e);
System.exit(1);
}
}
@BeforeAll
@BeforeClass
public static void startTestPageServer() throws Exception {
server = new Server(TEST_PAGE_SERVER_PORT);
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setResourceBase(getTestResourceFolder().getCanonicalPath());
server.setHandler(resourceHandler);
server.start();
}
/**
* Set up Jetty server to serve Allure Report.
*/
protected Server setUpServer(final String host, final int port, final Path reportDirectory) {
final Server server = Objects.isNull(host)
? new Server(port)
: new Server(new InetSocketAddress(host, port));
final ResourceHandler handler = new ResourceHandler();
handler.setRedirectWelcome(true);
handler.setDirectoriesListed(true);
handler.setResourceBase(reportDirectory.toAbsolutePath().toString());
final HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{handler, new DefaultHandler()});
server.setStopAtShutdown(true);
server.setHandler(handlers);
return server;
}
private static Server setupServer() throws Exception {
// String webDir = "target/classes/webui";
// String webDir = "src/main/resources/webui";
String webDir = WebServer.class.getClassLoader().getResource("webui").toExternalForm();
log.info("Base webdir is {}", webDir);
int httpPort = ConfigFactory.load().getInt("resource-reporting.visualization.webui-port");
log.info("Resource reporting web ui port is ", httpPort);
// Create Jetty server
Server server = new Server(httpPort);
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[] { "filter.html" });
resource_handler.setResourceBase(webDir);
WebSocketHandler wsHandler = new WebSocketHandler.Simple(PubSubProxyWebSocket.class);
ContextHandler context = new ContextHandler();
context.setContextPath("/ws");
context.setHandler(wsHandler);
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { context, resource_handler, new DefaultHandler() });
server.setHandler(handlers);
ClusterResources.subscribeToAll(callback);
return server;
}
public void addStaticResources(String basePath, String resourcePath) {
ContextHandler capHandler = new ContextHandler();
capHandler.setContextPath(basePath);
ResourceHandler resHandler = new ResourceHandler();
resHandler.setBaseResource(Resource.newClassPathResource(resourcePath));
resHandler.setEtags(true);
resHandler.setCacheControl(WebService.HANDLER_CACHE_CONTROL);
capHandler.setHandler(resHandler);
handlers.add(capHandler);
}
@Override
protected void before() throws Throwable {
server = new Server(0);
ResourceHandler rh = new ResourceHandler();
rh.setResourceBase("src/test/resources");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { rh, new DefaultHandler() });
server.setHandler(handlers);
server.start();
}
private void installSwagger(HandlerList handlers) {
LOGGER.debug("Adding Swagger documentation");
final ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(true); //
resourceHandler.setResourceBase(getClass().getResource("/swagger").toExternalForm());
ContextHandler swaggerHandler = new ContextHandler("/swagger/*");
swaggerHandler.setHandler(resourceHandler);
handlers.addHandler(swaggerHandler);
}