我尝试访问src/main/webapp/WEB-INF/imgs
文件夹中保存在Servlet中的一些图像,这样:
link
我尝试使用此代码在doPost
的{{1}}方法中访问这些图片:
Servlet
InputStream s = this.getClass().getClassLoader().getResourceAsStream("http://cardimgs.org/imgs/cardbackground1.jpg");
Movie movie = new Movie();
try {
byte[] bytes = IOUtils.toByteArray(s);
movie.setImage(bytes);
} catch (IOException e) {
e.printStackTrace();
}
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
// Store the image in App Engine's datastore
pm.makePersistent(movie);
} finally {
pm.close();
}
课程:
link 2,
我使用指定的Movie
创建url
的原因是因为我的InputStream
我有:
appengine-web.xml
我尝试定义静态文件。
我的问题,但是,通过上述代码,我无法访问我的文件并填写<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>myApplicationId</application>
<version>1</version>
<threadsafe>true</threadsafe>
<system-properties>
<property name="java.util.logging.config.file" value="WEB-INF/logging.properties" />
</system-properties>
<static-files>
<include path="/**.jpg"/>
<include path="/imgs" >
<http-header name="Access-Control-Allow-Origin" value="http://cardimgs.org" />
</include>
</static-files>
</appengine-web-app>
,因此显示为InputStream
,因此返回null
。
如何成功访问我的静态文件?
答案 0 :(得分:1)
ClassLoader.getResourceAsStream()
使用*类加载器**加载资源。因此,它在类路径中查找它们。 Web应用程序的类路径由WEB-INF/classes
和WEB-INF/lib
内的所有jar组成。它期望的路径看起来像com / mycompany / myproject / somefile.txt。它不能是HTTP URL。
您需要的是ServletContext.getResourceAsStream("/WEB-INF/imgs/cardbackground1.jpg")
。此方法从Web应用程序内的任何位置加载资源。