Martin Rohwedder
Martin Rohwedder

Reputation: 75

How to fetch my custom XML file through a servlet

I have a servlet which uses JAXB to unmarhsal and marshal an XML file, which I have made myself. My problem is that I can't unmarshal or marshal the XML file without giving the full local path to the XML file, the the marshaller. The problem with this, is that I can't deliver the project to my friend, without he need to edit the local path of the XML file. My code for the unmarshalling looks like this

ObjectFactory factory = new ObjectFactory();
CarList cl = factory.createCarList();

try {
    javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(cl.getClass().getPackage().getName());
    javax.xml.bind.Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
    cl = (CarList) unmarshaller.unmarshal(new java.io.File("/Users/martin/NetBeansProjects/Web-Mandatory-Assignment-Part1/web/resources/xml/Cars.xml")); //NOI18N
} catch (javax.xml.bind.JAXBException ex) {
    java.util.logging.Logger.getLogger("global").log(java.util.logging.Level.SEVERE, null, ex); //NOI18N
}

As u can see I need to use '/Users/martin/NetBeansProjects/Web-Mandatory-Assignment-Part1/web/resources/xml/Cars.xml' as the path for the file, but what i want it to do, is to use somehting like 'xml/resources/Cars.xml' instead. How can I make this work :)

Upvotes: 1

Views: 374

Answers (1)

Sam
Sam

Reputation: 6890

You can use ServletContext interface in javax.servlet package. For access to instance of this class use following code:

   http_request_instance.getServletContext();

There are useful methods in this interface such as:

  • getResource(String)
  • getResourceAsStream(String)
  • getRealPath(String)

for more information see:

Upvotes: 3

Related Questions