在 web 工程中,可以使用 ServletContext.getResource 或 .getResourceAsStream 來擷取資源。資源路徑由 “/” 開始,這個路徑是個相對路徑,對應 Web 工程的根目錄,或 WEB-INF/lib 中 jar 包的 META-INF/resources 目錄:
myApplication.war
WEB-INF
lib
library.jar
library.jar 有下面的包結構:
library.jar
MyClass1.class
MyClass2.class
stylesheets
common.css
images
header.png
footer.png
一般情況下,如果在 servlet 中要通路 stylesheets 和 images 檔案夾中的資源,需要手動地将它們提取到 web 工程的根目錄下。從 servlet 3.0 開始,允許将資源放入 jar 包的 META-INF/resources 目錄下:
library.jar
MyClass1.class
MyClass2.class
META-INF
resources
stylesheets
common.css
images
header.png
footer.png
在上面例子中,資源放入了 META-INF/resources 目錄中,是以不需要提取到根目錄也能直接通路。
應用會先掃描 web 根目錄下的資源,再掃描 jar 包中的資源,jar 包中資源的掃描順序是不定的。
文章來源:[url]http://www.aptusource.org/2014/04/java-ee-7-resource-packaging/[/url]