Referencing a file within Servlet

2019-07-04 00:01发布

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?

3条回答
来,给爷笑一个
2楼-- · 2019-07-04 00:31

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");
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-04 00:46

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.

查看更多
Ridiculous、
4楼-- · 2019-07-04 00:48

Provide a URIResolver to the Transformer.

查看更多
登录 后发表回答