问题 ServletContext getResource无法正常工作


我正在尝试使用 ServletContext.getResource 检索一个 java.net.url 参考图像文件(然后我将使用iText将其包含在PDF库中)。
我用的时候 ServletContext.getRealPath("picture.jpg"),我找回一个字符串URL。但是,getResource始终返回 null

例1

String picture = ServletContext.getRealPath("picture.jpg");
// picture contains a non-null String with the correct path
URL pictureURL = ServletContext.getResource(picture);
// pictureURL is always null

例2

URL pictureURL = ServletContext.getResource("picture.jpg");
// pictureURL is always null

那么构建指向我文件中的文件的java.net.URL对象的正确方法是什么? webapps/ 夹?为什么 getRealPath 工作但不是 getResource

如果它有帮助,这是我的文件夹结构

webapps -> mySite -> picture.jpg

我的照片是否需要存储在其中 WEB-INF 要么 WEB-INF/classes 被阅读 getResource


2225
2018-06-09 14:23


起源



答案:


返回映射到指定路径的资源的URL。路径必须以“/”开头,并且被解释为相对于当前上下文根。

因此,您必须提供上下文相关的完整路径。例如:

URL pictureURL = servletContext.getResource("/images/picture.jpg");

(注意较低的情况 servletContext 变量)


10
2018-06-09 14:27



添加前导斜杠修复了问题 - David


答案:


返回映射到指定路径的资源的URL。路径必须以“/”开头,并且被解释为相对于当前上下文根。

因此,您必须提供上下文相关的完整路径。例如:

URL pictureURL = servletContext.getResource("/images/picture.jpg");

(注意较低的情况 servletContext 变量)


10
2018-06-09 14:27



添加前导斜杠修复了问题 - David


getRealPath() 提供资源的操作特定绝对路径,同时 getResource() 接受相对于上下文目录的路径,参数必须以“/”开头。尝试 ServletContext.getResource ("/picture.jpg") 代替。

文档: 的getResource


2
2018-06-09 14:37