Referencing a file within Servlet

丶灬走出姿态 提交于 2020-01-14 19:15:31

问题


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?


回答1:


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");



回答2:


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.




回答3:


Provide a URIResolver to the Transformer.



来源:https://stackoverflow.com/questions/6889728/referencing-a-file-within-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!