如何从Netbeans上的Servlet中的项目类路径获取图像 [英] How to get the image from project classpath in Servlet on Netbeans

查看:220
本文介绍了如何从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.

这篇关于如何从Netbeans上的Servlet中的项目类路径获取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆