I have a plain java class in a web application and want to read a configuration file under WEB-INF
folder. I know the way to access the file if its in the classpath (WEB-INF/classes
folder). Since WEB-INF/classes
folder is meant for .class
files, I want to keep my configuration file under WEB-INF
folder only.
Can anyone tell me how I can access it from my java class?
WEB-INF. This directory, which is contained within the Document Root, is invisible from the web container. It contains all resources needed to run the application, from Java classes, to JAR files and libraries, to other supporting files that the developer does not want a web user to access.
No, it's not in the classpath.
You should put in WEB-INF any pages, or pieces of pages, that you do not want to be public.
ServletContext.getResourceAsStream() will load a file from a given path relative to the root of the WAR file. Something like:
ServletContext ctx;
InputStream configStream = ctx.getResourceAsStream("/WEB-INF/config.properties");
The major issue here is that you need access to the servlet context to be able to do this. You have that in a servlet or a filter, but not in a non-web component further back in the application. You have a few options:
You can get the absolute path of servlet using getRealPath()
method of ServletContext
and then append WEB-INF
to the path you get. I think this is very basic there may be some other answers as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With