如何从 servlet 访问 www 目录中的文件?
使用 tomcat 6,我在 www/templates/templatefile.html 中创建了一个模板,
如何从 servlet 访问它?我想读取 html 文件并解析它。
我尝试使用 request.getRealPath(request.getServletPath()) 获取真实路径 并从那里转到模板目录,但由于某种原因它仍然找不到该文件。
Using tomcat 6, i created a template inside www/templates/templatefile.html
how do I access it from a servlet ? i want to read the html file and parse it.
I tried getting the real path using request.getRealPath(request.getServletPath())
and from there to go to the templates directory but for some reason it still can't find the file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设
www
是公共 Web 内容根目录中的文件夹,那么您可以使用ServletContext#getRealPath()
将相对 Web 路径转换为绝对磁盘文件系统路径,如下所示:笔记当 WAR 未展开时,这将不起作用(默认修剪中的 Tomcat 会这样做,但可以将其配置为不这样做)。如果您最终想要的只是拥有一个
InputStream
,那么您宁愿使用ServletContext#getResourceAsStream()
代替。Assuming that
www
is a folder in the public web content root, then you can useServletContext#getRealPath()
to convert a relative web path to an absolute disk file system path as follows:Note that this won't work when the WAR is not expanded (Tomcat in default trim does it, but it can be configured not to do that). If all you want to end up is having an
InputStream
of it, then you'd rather like to useServletContext#getResourceAsStream()
instead.