希望在 Jetty 中使用多个静态目录。服务器运行时:
http://localhost:8282/A
http://localhost:8282/B
http://localhost:8282/C
以下失败:
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setWelcomeFiles(new String[]{"index.html"});
resource_handler.setResourceBase(HTML_SITE);
ResourceHandler resource_handler1 = new ResourceHandler();
resource_handler1.setWelcomeFiles(new String[]{"index.html"});
resource_handler1.setResourceBase(HTML_CLIENTZONE_SITE);
// deploy engine
WebAppContext webapp = new WebAppContext();
String dir = System.getProperty("user.dir");
webapp.setResourceBase(getWebAppPath());
webapp.setContextPath("/");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{resource_handler,resource_handler1 ,webapp, new DefaultHandler()});
server.setHandler(handlers);
如何添加多个静态资源目录?
最佳答案
从 6.1.12 开始,通过对 WebAppContext 的基础资源使用 ResourceCollection 来支持这一点:
Server server = new Server(8282);
WebAppContext context = new WebAppContext();
context.setContextPath("/");
ResourceCollection resources = new ResourceCollection(new String[] {
"project/webapp/folder",
"/root/static/folder/A",
"/root/static/folder/B",
});
context.setBaseResource(resources);
server.setHandler(context);
server.start();
要随后打开文件,请使用 ServletContext(例如,WebAppContext),它可以是接口(interface)定义的一部分,例如:
/**
* Opens a file using the servlet context.
*/
public default InputStream open( ServletContext context, String filename ) {
String f = System.getProperty( "file.separator" ) + filename;
return context.getResourceAsStream( f );
}
如:
InputStream in = open( context, "filename.txt" );
这将打开
filename.txt
如果它存在于给定目录之一中。请注意,getResourceAsStream 将返回 null
,而不是抛出异常,所以检查它是个好主意: public default InputStream validate( InputStream in, String filename )
throws FileNotFoundException {
if( in == null ) {
throw new FileNotFoundException( filename );
}
return in;
}
然后你可以更新
open
方法如下:return validate( context.getResourceAsStream( filename ), filename );
关于directory - 向 jetty 添加多个资源目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11410388/