![](/img/trans.png)
[英]Reading from src/main/resources gives NullPointerException
[英]Reading resources from src/main/resources/.. in spring-MVC
我制作了一個 controller,它將圖像(* .png)文件返回給適當的請求。
controller的代碼寫在下面。
@Controller
public class ImageController {
@GetMapping(value = "/ImageStore.do", produces = MediaType.IMAGE_PNG_VALUE)
public @ResponseBody byte[] getStoreImage(HttpServletRequest request) throws IOException {
String image_name = request.getParameter("image_name");
Resource resource = null;
try {
resource = new ClassPathResource("/images/stores/" + image_name);
if(resource == null) {
throw new NullPointerException();
}
} catch(NullPointerException e) {
resource = new ClassPathResource("/images/stores/noimage.png");
}
InputStream inputStream = resource.getInputStream();
return IOUtils.toByteArray(inputStream);
}
}
Q1。 如果請求參數錯誤,或者請求參數image_name
的文件名不存在,我添加了try-catch
短語來發送noimage.png
。 但它似乎不起作用,它給我的日志說class path resource [images/stores/noima.png] cannot be opened because it does not exist
(如果您需要知道完整的堆棧跟蹤,我將在下面評論.)
Q2。 我在文件夾/resources/images/stores/
中有 2 個圖像文件, hello.png
和noimage.png
。 我可以正確讀取noimage.png
,但是如果我發出請求localhost:8080/ImageStore.do?image_name=hello.png
,那么它會出錯,在 Q1 中進行相同的日志。
沒有理由認為構造函數會產生null
值。
您得到的異常可能來自getInputStream
方法,該方法記錄為 throw
FileNotFoundException - 如果底層資源不存在
IOException - 如果內容 stream 無法打開
稍作調整可能會有所幫助
@Controller
public class ImageController {
@GetMapping(value = "/ImageStore.do", produces = MediaType.IMAGE_PNG_VALUE)
public @ResponseBody byte[] getStoreImage(HttpServletRequest request) throws IOException {
InputStream is = null;
try {
String image_name = request.getParameter("image_name");
is = new ClassPathResource("/images/stores/" + image_name).getInputStream();
} catch(FileNotFoundException e) {
is = new ClassPathResource("/images/stores/noimage.png").getInputStream();
}
return IOUtils.toByteArray(is);
}
}
您應該包括堆棧跟蹤和異常消息,這可能有助於理解您的第二個查詢,但我會檢查該文件是否確實存在,以及您使用的確切名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.