getServletContext().getRealPath() doesn't work in controller (NPE), but works in jsp

Juraj Vlahović picture Juraj Vlahović · Mar 25, 2013 · Viewed 39k times · Source

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.

Answer

Juraj Vlahović picture Juraj Vlahović · Mar 26, 2013

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);