如何从Netbeans上的Servlet中的项目类路径获取图像

问题描述:

我在Netbeans的网页目录中创建了一个 / header 文件夹,并添加了一个名为 header.png的图像 。现在我想使用以下代码在servlet中访问此图像文件:

I made a /header folder in the web pages directory in Netbeans and added an image named header.png. Now I want to access this image file in a servlet using the following code:

BufferedImage image = ImageIO.read(getClass().getResource(" /header/header.png"));

但这不会发生,它会出现以下错误:

But this is not happening, it gives the following error:


java.lang.IllegalArgumentException:input == null!

java.lang.IllegalArgumentException: input == null!

以下是我的项目的目录结构:

Below is my project's directory structure:

如何导致此错误以及如何解决?

How is this error caused and how can I solve it?

Class#getResource()从类路径返回资源,而不是从公共Web内容返回。

The Class#getResource() returns an resource from the class path, not from the public web content.

您需要 ServletContext #getResource() 或更好, getResourceAsStream() 而不是。

You need ServletContext#getResource(), or better, getResourceAsStream() instead.

BufferedImage image = ImageIO.read(getServletContext().getResourceAsStream("/header/header.png"));

(请注意我也从路径中删除了尾随空格)

请注意,有些用户可能会建议你使用 ServletContext#getRealPath(),但你不应该使用它在这种特殊情况下,当容器配置为将部署的WAR扩展到内存而不是本地磁盘文件系统时,可能会返回 null

Note that some users may suggest you to use ServletContext#getRealPath(), but you shouldn't use it in this particular case as that may return null when the container is configured to expand the deployed WAR into memory instead of local disk file system.