Discussions

Web tier: servlets, JSP, Web frameworks: How to use relative path with respect to Servet to load a xml

  1. Hi All
    MyServlet has to read a xml document at the serverside. Am using SAXparser to read the xml doc. But If a place my xml document in bin folder of Tomcat then its able to load the file and parsing. If suppose I keep the document in WEB-INF/classes folder then I need to provide the absoulute path to reach the document. Is there any way of reading the document by using the relative path with respect to the servlet.
         
    Thanks in advance
    Anila
  2. MyServlet has to read a xml document at the serverside. Am using SAXparser to read the xml doc. But If a place my xml document in bin folder of Tomcat then its able to load the file and parsing. If suppose I keep the document in WEB-INF/classes folder then I need to provide the absoulute path to reach the document. Is there any way of reading the document by using the relative path with respect to the servlet.


    This can be done by using ServletContext.getResourceAsStream() method.


    The following code may help you:

    InputStream inputStream = getServletContext().getResourceAsStream("/WEB-INF/classes/xyz.xml");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    ....
    Document xmlDocument = db.parse(inputStream);