Question

Within a jsp file i'm trying to navigate to load xml file. The location of the JSP file is

/projectFolder/layout/applicationName/index.jsp

the location of the xml file

/projectFolder/data/files/myfile.xml

The location of the project folder is different in each environment, example: in my local pc the location is:

c:\myApps\BPServer\tomcat\webapps\projectFolder

when i use the following code:

<c:set var="xmlfile" value="${pageContext.request.contextPath}/data/files/myfile.xml"/>

The value of xmlFile is set to:

c:\projectFolder\data\files\myfile.xml 

However the strange thing is that if i use the xmlfile as href then the correct path and file is located:

<jsp:attribute name="rightContent"><a href="${xmlfile}">XML FILE</a></jsp:attribute>

Any idea how can i get the correct file path in order to the following to work:

boolean canLocateFile = fileExists(xmlfile);

    public static boolean fileExists(String filepath)
        {
            File f = new File(filepath);
            return f.exists();
        }
Was it helpful?

Solution

You can get root path of application from ServletContext.

If you have relative path of file, you can get it's real path using servletContext.getRealPath().

eg:

String realPath = servletContext.getRealPath("/data/files/myfile.xml");

You can also get root path of your application using servletContext.getContextPath(). Root path can then be used to refer to your file. eg:

String rootPath = servletContext.getContextPath();
String filePath = rootPath + "/data/files/myfile.xml";

In case servletContext is not accessible to you in your class, you can store root path of your application in init-param or properties, and can use it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top