Try using the classloader object.
ClassLoader loader = Thread.currentThread().getContextClassLoader();
This will let you access files on the classpath. Look at the getResource
method that returns a URL
.
I notice in your screenshot that eclipse is not categorizing "src/main/webapp" under "Java Resources". I think this means eclipse is not putting that webapp folder in your classpath. You may need to configure the eclipse build path. In brief, right-click on the project, click properties, click "build path" on the left, select the "source" tab, and add "src/main/webapp".
It depends on your classpath entries in your eclipse. As it seems to be a maven project, so most likely your webapp directory should be part of classpath. And if that is the case, then relative url for your file will start from directory images,like this:
images/add.png
The relative path starts from /
.
If you are accessing the image in JSP file then you can try with core tag library.
for example:
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:url value="/images/add.png"/>
If you want to access the image file at server side then put the file under resources
folder that goes directly to classpath.
You can try with Spring ClassPathResource
to read the resources from classpath that are stored directly under resources
folder.
For example:
try (InputStream in = new ClassPathResource("/images/add.png").getInputStream())
{
...
}
catch (IOException e)
{
....
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.