Reputation: 283
I have a webapp with a subdirectory called msc. I keep an xml file in a subdirectory of msc called _etc/xml.
The absolute path on my local machine is c:/myproject/tomcat/webapps/javawork/msc/_etc/xml/msc_approval_managers.xml
I want a jsp file in the msc directory to be able to do get the xml file and parse through it to grab text to be used in the HTML of the jsp page. I understand it may not be the best programming practices to put java scriptlet code in a jsp file, but that is what I am required to do, so please don't give me grief about that. I can't control that part. Eventually my code will be put onto a production server, so I need to use a relative path to get the xml file. In ColdFusion it was incredibly simple (I have to translate a CF site to Java), and was done in three lines like so:
<!--- Set path to msc_approval_managers.xml --->
<cfset pathToXml = ExpandPath("/msc/_etc/xml/msc_approval_managers.xml")>
<!--- Read xml file into string variable --->
<cffile action="read" file="#pathToXml#" variable="xmlDoc">
<!--- Parse xml into an xml object --->
<cfset XMLDoc = XmlParse(xmlDoc)>
I could then just loop through XMLDoc
. Obviously it's not that simple in Java. I have the code to parse the xml and loop through it. I just need to find a way to get the file itself using a relative path, so the code can just be uploaded to the production server and know where the file is located (on that server) without an absolute path. Can this be done in Java, specifially in a jsp page?
Any advice would be appreciated, and again, please do not question why it has to be in a jsp page, that is just the requirement I have to work with for the task at hand. Thanks.
Upvotes: 0
Views: 2445
Reputation: 360
Thats really strange task for jsp ... but you can get the real path and then load and parse the file with your code.
<%
String path = request.getServletContext().getRealPath("/msc/_etc/xml/msc_approval_managers.xml");
out.write(path);
%>
Or to get the input stream:
<%
java.io.InputStream stream = request.getServletContext().getResourceAsStream("/msc/_etc/xml/msc_approval_managers.xml");
if (stream != null) out.write("Got input stream ..." );
%>
Upvotes: 2