Sometimes the easiest things are also the easiest to miss (or to forget :-) ). Therefore, in order to have this once and for all in one place - the quickest guide how to access files in a servlet environment (Spring Boot application in my case).
Can be anything, most probably a configuration file that is packed with WAR during package preparation stage. In case of good old Maven - all of the resources (by default src/main/resources) will end up in the classpath. Access - via context class loader.
For example:
As a last word - be __very__ cautious when planning to use ServletContext.getRealPath(). Why? Just take a look here: http://stackoverflow.com/questions/12160639/what-does-servletcontext-getrealpath-mean-and-when-should-i-use-it
1. Classpath resource
A file that is present in a classpath (typically /WEB-INF/classes, /WEB-INF/lib).Can be anything, most probably a configuration file that is packed with WAR during package preparation stage. In case of good old Maven - all of the resources (by default src/main/resources) will end up in the classpath. Access - via context class loader.
For example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); | |
InputStream inputStream = classLoader.getResourceAsStream("class/path/relative/file"); |
2. Web resource
All of the web application files - including static content (images, styles, html, ...) and files that are loaded into classpath (JARs from /WEB-INF/lib etc.) can be accessed this way. The only requirement is the presence of a ServletContext.
PRO TIP: In a Spring application, the ServletContext can be simply autowired into a service requiring it.
For example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Autowired private ServletContext context; | |
... | |
InputStream inputStream = context.getResourceAsStream("/app/content/index.html"); |
Brak komentarzy:
Prześlij komentarz