Cant retrieve an images from the WEB-INF folder ussing classLoader.getResourceAsStream()

混江龙づ霸主 提交于 2019-12-01 08:53:32

I think you're confusing ClassLoader#getResourceAsStream() with ServletContext#getResourceAsStream(). The former only loads resources from the classpath while the later only loads resources from the webcontent (there where your /WEB-INF folder also is).

You need to put those resources in the classpath. If you're using an IDE, then most straightforward way is to just drop them in any package in the Java source folder. It'll end up in /WEB-INF/classes after build, which is part of the classpath.

Lets assume that you've a package com.example.resources.images and you've dropped logoemailtemplate.png file in there, then you can load it by the following fileName.

String fileName = "/com/example/resources/images/logoemailtemplate.png";

An alternative is to add /WEB-INF/resources folder to the classpath. In an IDE like Eclipse, you can do that by adding it as Source folder in project's build path. Then you can load it by the following fileName.

String fileName = "/images/logoemailtemplate.png";

This is however not the common practice.

As far as I know the classLoader can only access WEB-INF/classes and WEB-INF/lib but not WEB-INF/resources. Try to put the file in the classes sub-folder.

You must use ServletContext.getResourceAsStream() to load a file from a war. ClassLoader.getResourceAsStream loads a class from the classpath.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!