I’m new to Spring MVC. I created a new spring controller method that takes an fileoutputstream and writes xml to it as follows:
@RequestMapping(value = "/xml", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)
public final void getMappingsAsXML(HttpServletResponse response) {
Customer customer = getCustomerMappings();
try {
// Generates xml file
xmlHelper.save(customer, new StreamResult(new FileOutputStream("/WEB-INF/content/customermapping.xml")));
// print to browser
// read generated file and write to response outputsteam
} catch (XmlMappingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
However, the above code throws the below exception:
java.io.FileNotFoundException: /WEB-INF/content/customermapping.xml (No such file or directory)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:194)
at java.io.FileOutputStream.<init>(FileOutputStream.java:84)
The content directory already exists in the WEB-INF folder. Also, are there any better ways to write a file to browser in spring?
[BTW, I’m using maven.]
By using a path of
/WEB-INF/content/customermapping.xmlyou are telling Java to write a file namedcustomermapping.xmlto theWEB-INF/contentdirectory at the root of the drive. This doesn’t sound like what you want.Try removing the leading
/.However it’s probably a bad idea to write to files within the same directory hosting your web application, as some servlet containers like Tomcat simply remove the entire directory when you undeploy the application (with the default settings). Much better to write to a directory external to the webapp.