Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing a file within Servlet

When I reference to a DTD file in my code, I don't know how to reference to it within my project's folder. e.g : If my project's name is Moo, I'd want to refernce the DTD at /Moo/WEB-INF/courses.dtd.

TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = null;  

try { trans = transfac.newTransformer();   }
catch (TransformerConfigurationException e) { }

trans.setOutputProperty(OutputKeys.INDENT, "yes");  
trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "/Moo/WEB-INF/courses.dtd");

But it doesn't find it. How can I reference it?

I was offered a solution using getRealPath problem is since my project will be read as a .war file this is not good. What should I do?

like image 471
Nachshon Schwartz Avatar asked Dec 12 '25 15:12

Nachshon Schwartz


2 Answers

First of all, do not include "Moo". For servlet root is one level up from WEB-INF. Not sure that OutputKeys.DOCTYPE_SYSTEM wants relative path. Absolute path is:

String path = getServletContext().getRealPath("/WEB-INF/courses.dtd");
like image 119
Nulldevice Avatar answered Dec 14 '25 05:12

Nulldevice


So you're in the process of generating an XML document using XSLT. You want the document to be indented (OutputKeys.INDENT, "yes"), and you want it to contain a DOCTYPE with a SYSTEM reference (OutputKeys.DOCTYPE_SYSTEM, "...").

Now it's not likely that you want the real path of $WebAppRoot/Moo/WEB-INF/courses.dtd as the SYSTEM reference. Will it not rather be a URL, like http://www.example.com/some/dir/courses.dtd? And then the DTD should be available from that URL, of course. What resides in WEB-INF cannot be accessed via HTTP, at least not via the Servlet container.

If, on the other hand, you want to make the document and the DTD available only on the server that's building the document, then proceed as suggested by Nulldevice, with the caveats added in the comments.

like image 36
Lumi Avatar answered Dec 14 '25 03:12

Lumi