Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 682
Newbie Avatar asked Oct 14 '12 15:10

Newbie


People also ask

What is WEB-INF folder in Java?

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.

Is WEB-INF in classpath?

No, it's not in the classpath.

What kind of files should be put under Folder WEB-INF?

You should put in WEB-INF any pages, or pieces of pages, that you do not want to be public.


2 Answers

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
like image 147
Tom Anderson Avatar answered Sep 21 '22 15:09

Tom Anderson


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.

like image 22
Abubakkar Avatar answered Sep 25 '22 15:09

Abubakkar