Tuesday, April 22, 2014

How to access a file under WEB-INF folder in java class

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:
  • Make the servlet context available from the web layer to the service layer, via an application-scoped variable, or injection, or some other way
  • Put the resource-loading code in the web layer, and expose that to the service layer
  • Load the configuration in the web layer, and pass it on to the service layer

No comments:

Post a Comment