Accessing Resources in the WAR/WEB-INF Directory with ServletContext
Introduction:
Java web applications often store essential resources within the WAR/WEB-INF directory. To access these resources, developers can leverage the ServletContext API.
Question:
How can you create the correct path to a resource located in the WAR/WEB-INF folder, such as "/war/WEB-INF/test/foo.txt"?
Answer:
There are two primary methods for constructing the path to resources in the WAR/WEB-INF directory using ServletContext:
1. getRealPath() Method:
If the WAR file has been expanded into a set of files, you can use the getRealPath() method:
ServletContext context = getContext(); String fullPath = context.getRealPath("/WEB-INF/test/foo.txt");
This will return the complete system path to the resource.
2. getResource() or getResourceAsStream() Methods:
These methods can be used regardless of whether the WAR file is expanded or not:
ServletContext context = getContext(); URL resourceUrl = context.getResource("/WEB-INF/test/foo.txt"); // for URL InputStream resourceContent = context.getResourceAsStream("/WEB-INF/test/foo.txt"); // for input stream
Additional Notes:
The above is the detailed content of How to Access Resources in the WAR/WEB-INF Directory with ServletContext?. For more information, please follow other related articles on the PHP Chinese website!