加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – ServletContext getResource不工作

发布时间:2020-12-14 16:38:39 所属栏目:Java 来源:网络整理
导读:我试图使用ServletContext.getResource来检索对图像文件的 java.net.url引用(然后我将使用iText包含在PDF库中). 当我使用ServletContext.getRealPath(“picture.jpg”)时,我收到一个字符串URL.但是,getResource总是返回null. 示例1: String picture = Servl
我试图使用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

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

万一有帮助,这里是我的文件夹结构

webapps -> mySite -> picture.jpg

我的图片需要存储在WEB-INF或WEB-INF / classes中才能被getResource读取?

解决方法

Returns a URL to the resource that is mapped to a specified path. The path must begin with a “/” and is interpreted as relative to the current context root.

所以你必须提供上下文相对的完整路径.例如:

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

(注意下面的servletContext变量)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读