如何从 servlet 访问 www 目录中的文件?

发布于 2024-11-16 06:07:20 字数 201 浏览 9 评论 0原文

使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

£冰雨忧蓝° 2024-11-23 06:07:20

假设 www 是公共 Web 内容根目录中的文件夹,那么您可以使用 ServletContext#getRealPath() 将相对 Web 路径转换为绝对磁盘文件系统路径,如下所示:

String relativeWebPath = "/www/templates/templatefile.html";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
InputStream input = new FileInputStream(file);
// ...

笔记当 WAR 未展开时,这将不起作用(默认修剪中的 Tomcat 会这样做,但可以将其配置为不这样做)。如果您最终想要的只是拥有一个 InputStream ,那么您宁愿使用 ServletContext#getResourceAsStream() 代替。

String relativeWebPath = "/www/templates/templatefile.html";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// ...

Assuming that www is a folder in the public web content root, then you can use ServletContext#getRealPath() to convert a relative web path to an absolute disk file system path as follows:

String relativeWebPath = "/www/templates/templatefile.html";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
InputStream input = new FileInputStream(file);
// ...

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 use ServletContext#getResourceAsStream() instead.

String relativeWebPath = "/www/templates/templatefile.html";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文