提到靜態資源加載不得不提到的一個類,這是jetty提供的靜態資源處理類。html
Server server = new Server(8080);
//封裝靜態資源訪問路徑
ContextHandler contextHandler = new ContextHandler("/index");
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(true);
resourceHandler.setWelcomeFiles(new String[]{"index.html"});
resourceHandler.setResourceBase(Objects
.requireNonNull(Application.class.getClassLoader().getResource("template")).getPath());
contextHandler.setHandler(resourceHandler);
server.setHandler(contextHandler);
server.start();
server.join();
複製代碼
因爲 ResourceHandler 並未提供訪問路徑匹配,故再封裝到 ContextHandler。java
log.info(Application.class.getClassLoader().getResource("template").getPath());
複製代碼
打印結果:json
server.Application - file:/home/jawliet/Projects/json-rpc-demo/target/json-rpc-demo-1.0-SNAPSHOT-jar-with-dependencies.jar!/template
複製代碼
而這個路徑是沒法直接訪問的。運維
這裏很少廢話,直接上代碼工具
Server server = new Server(8080);
//封裝靜態資源訪問路徑
ContextHandler contextHandler = new ContextHandler("/index");
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(true);
// log.info(Application.class.getClassLoader().getResource("template").getPath());
// resourceHandler.setResourceBase(Objects
// .requireNonNull(Application.class.getClassLoader().getResource("template")).getPath());
resourceHandler.setBaseResource(Resource.newResource(Application.class.getClassLoader().getResource("template")));
resourceHandler.setWelcomeFiles(new String[]{"index.html"});
contextHandler.setHandler(resourceHandler);
server.setHandler(contextHandler);
server.start();
server.join();
複製代碼
這裏能夠看到,ResourceHandler 除了提供路徑的資源指定外,還提供類直接 Resource 的指定方式,其實在不少能指定路徑的地方都提供類 Resource 的指定方式,如:ui
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStoreResource(Resource.newResource(Application.class.getClassLoader().getResource("keystore.jks")));
複製代碼
Resource 有多個子類,感興趣的能夠本身研究