5

I am trying to add image to my pdf file. Image is located in "WebContent/img/image.png". First I save relative path to string and then I convert this relative path to real path.

String relativeWebPath = "/img/image.png";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
Image image1 = Image.getInstance(absoluteDiskPath);

Even this

String absoluteDiskPath = getServletContext().getRealPath("/");

doesn't work.

I tried a few variations when I was defining relative path, but couldn't make any of them to work. I always get nullPointerException when this line String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath); tries to execute. Am I doing something wrong with relative path or something else? I don't know if this is relevant but I am using Spring.

@RequestMapping(value = "/exportPhonebook.html", method = RequestMethod.POST)
public void exportPhonebook(Model model, HttpServletResponse response) {
    try {
        setResponseHeaderPDF(response);
        Document document = new Document();
        ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
        PdfWriter pdfWriter = null;
        pdfWriter = PdfWriter.getInstance(document, baosPDF);
        PageNumbersEventHelper events = new PageNumbersEventHelper();
        pdfWriter.setPageEvent(events);
        document.open();
        addMetaData(document);
        addTitlePage(document);
        String relativeWebPath = "/img/image.png";
        String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
        Image image1 = Image.getInstance(absoluteDiskPath);
        document.add(image1);
        addContent(document);
        document.close();
        pdfWriter.close();
        OutputStream os = response.getOutputStream();
        baosPDF.writeTo(os);
        os.flush();
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

This is how I used it in jsp:

<input type="hidden" value="<%=getServletContext().getRealPath("/") %>" name="path">

I pass this to controller and add relative path to this path.

path = path + "img\\image.png";
Image image = Image.getInstance(path);

THis works just fine. I don't understand why this doesn't work in my controller.

Juraj Vlahović
  • 400
  • 2
  • 4
  • 12

3 Answers3

9

I was missing this:

ServletContext servletContext = request.getSession().getServletContext();

now it works from controller.

ServletContext servletContext = request.getSession().getServletContext();
String relativeWebPath = "img/image.png";
String absoluteDiskPath = servletContext.getRealPath(relativeWebPath);
Juraj Vlahović
  • 400
  • 2
  • 4
  • 12
  • It won't work if you run spring boot jar via command line. always use servletContext.getResource(path); to make compatible from both side. – Asad Khan Nov 01 '20 at 13:33
1

http://ananthkannan.blogspot.ru/2009/12/servletcontextgetrealpath-returns-null.html

Another weird behavior from weblogic when webapp is deployed as WAR. ServletContext.getRealPath() returns null when deployed as WAR but it works ok when deployed as exploded. There are two ways we can fix this issue when you still want to deploy as WAR but would like to get over with this issue: 1. Go to server admin console->Domain-> Web applications. Click the checkbox of Archived Real Path Enabled. This should make an entry into domain config.xml as below. true

  1. Second option is at webapp level by updating weblogic.xml as below: true The value of set in the web app has precedence over the value set at the domain level. The default value of this property is false.
Denis Orlov
  • 130
  • 4
0

Try to start your relative path from the /WEB-INF/ folder since /img/image.png can be at more than one place in your folder structure, how could you then get the absolute path.

See the Documentation states about getRealPath():

This method returns null if the servlet container is unable to translate the given virtual path to a real path.

Which means you should check the returned value before using it.

CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
  • Just to make sure you are not providing the content from a .war archive are you? – CloudyMarble Mar 25 '13 at 14:49
  • Try to get your root by outputting servletContext.getRealPath("/") and then build the relative path to your image file. – CloudyMarble Mar 25 '13 at 14:52
  • I Will try that first thing tomorrow. – Juraj Vlahović Mar 25 '13 at 18:34
  • 1
    `servletContext.getRealPath("/")` doesn't work in my controller, I also get NPE. But when I put this `" name="path">` in my jsp, and pass that to the controller I get absolute path like this `C:\Documents and Settings\JVlahovic\Desktop\Web aplikacije u javi\WORKSPACE\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\phonebook\` then I remove this `.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\phonebook\` and add this `phonebook\WebContent\img\image.png` The path I get manage to get my Image. – Juraj Vlahović Mar 26 '13 at 09:54
  • Does it work then?, you need to find the realtive path to the file according tot the real path. or just use Image.getInstance(absolutepathToYourFile) – CloudyMarble Mar 26 '13 at 10:00
  • am I missing something in my controller maybe? – Juraj Vlahović Mar 26 '13 at 10:01
  • RelativePath is known but I can't get realPath with this line `servletContext.getRealPath(relativePath)` in my controller. But I can get it from jsp. I don't know why this line doesn't work in my controller. I always get NPE. – Juraj Vlahović Mar 26 '13 at 10:03