从 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),它可以是接口定义的一部分,例如:
/**
* 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 );
}
Such as:
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 );