Use the method ServletContext.getRealPath(), or even better ServletContext.getResourceAsStream(). Both of these methods take website relative paths. The first returns a String representing the actual location on disk, the second returns an actual input stream to that file.
getResourceAsStream() is more reliable, as it will work even in situations where the application is deployed as an unexploded WAR file, whereas getRealPath() would return null, or an unhelpful value.
ServletContext application = getServletConfig().getServletContext();
// method 1
String fileName = application.getRealPath("/xml/first_top.xml");
File inFile = new File(fileName);
Document doc = docBuilder.parse(inFile);
// or method 2 (recommended)
InputStream in = application.getResourceAsStream("/xml/first_top.xml");
Document doc = docBuilder.parse(in);
If you are in a JSP, the "application" variable is already defined for you.
Cheers,
evnafets
hello
I am sorry i still have a problem.
when i tried your mehtod 2 as follows it works
InputStream in = application.getResourceAsStream("/xml/first_top.xml");
Document doc = docBuilder.parse(in);
But the strange thing is that i just did n't define 'application' as a servletcontext object and when i added the line
ServletContext application = getServletConfig().getServletContext();
it raises an jasperexception
Why is this happen ? is it because application is an implicit object ?
hello
I am sorry i still have a problem.
when i tried your mehtod 2 as follows it works
InputStream in = application.getResourceAsStream("/xml/first_top.xml");
Document doc = docBuilder.parse(in);
But the strange thing is that i just did n't define 'application' as a servletcontext object and when i added the line
ServletContext application = getServletConfig().getServletContext();
it raises an jasperexception
Why is this happen ? is it because application is an implicit object ?
>is it because application is an implicit object ?
Yes. Sorry for the confusion.
You only need the line: ServletContext application = getServletConfig().getServletContext(); if you are in a servlet. It is implicitly defined in a JSP.
I prefer not to write scriptlet code in JSP.
This kind of code is normally better suited to a servlet.
However I do like standardising the variable name, so started using "application" as my variable in servlets.