Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

jakarta ee - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...