Question

I have multimodule project

Project
  |--src
      |-JavaFile.java

Web-Project
  |-Web-Content
    |-images
    |   |-logo.PNG
    |-pages
    |-WEB-INF
  1. regular java module - contains src with all java files
  2. dynamic web project module - contains all web related stuff

eventually regular java module goes as a jar file in dynamic web module in lib folder

Problem

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.

Was it helpful?

Solution

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.

See also:


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);
// ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top