Reputation: 79
I have multimodule project
Project
|--src
|-JavaFile.java
Web-Project
|-Web-Content
|-images
| |-logo.PNG
|-pages
|-WEB-INF
eventually regular java module goes as a jar file in dynamic web module in lib folder
java file after compilation looks for an image file in c:\ibm\sdp\server completepath\logo.png rather in context. File is defined in java file as below for iText:
Image logo = Image.getInstance("/images/logo.PNG");
Please suggest how can I change my java file to refer to image. I am not allowed to change my project structure.
Upvotes: 0
Views: 1012
Reputation: 1108922
You need to use ServletContext#getResource()
or, better, getResourceAsStream()
for that. It returns an URL
respectively an InputStream
of the resource in the web content.
InputStream input = getServletContext().getResourceAsStream("/images/logo.PNG");
// ...
This way you're not dependent on where (and how!) the webapp is been deployed. Relying on absolute disk file system paths would only end up in portability headache.
Update: as per the comments, you seem to be using iText (you should have clarified that a bit more in the question, I edited it). You can then use the Image#getInstance()
method which takes an URL
:
URL url = getServletContext().getResource("/images/logo.PNG");
Image image = Image.getInstance(url);
// ...
Update 2: as per the comments, you turn out to be sitting in the JSF context (you should have clarified that as well in the question). You should use ExternalContext#getResource()
instead to get the URL
:
URL url = FacesContext.getCurrentInstance().getExternalContext().getResource("/images/logo.PNG");
Image image = Image.getInstance(url);
// ...
Upvotes: 1