[英]How to get the image from project classpath in Servlet on Netbeans
我在 Netbeans 的網頁目錄中創建了一個/header
文件夾,並添加了一個名為header.png
的圖像。 現在我想使用以下代碼在 servlet 中訪問此圖像文件:
BufferedImage image = ImageIO.read(getClass().getResource(" /header/header.png"));
但這並沒有發生,它給出了以下錯誤:
java.lang.IllegalArgumentException: 輸入 == null!
下面是我項目的目錄結構:
這個錯誤是如何引起的,我該如何解決?
Class#getResource()
從類路徑返回資源,而不是從公共 Web 內容返回。
您需要ServletContext#getResource()
,或者更好的是getResourceAsStream()
。
BufferedImage image = ImageIO.read(getServletContext().getResourceAsStream("/header/header.png"));
(請注意,我也從路徑中刪除了尾隨空格)
請注意,有些用戶可能會建議您使用ServletContext#getRealPath()
,但您不應該在這種特殊情況下使用它,因為當容器配置為將部署的 WAR 擴展到內存而不是本地磁盤文件系統時,它可能會返回null
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.