Reputation: 181
I have the following structure in a Java Web Application:
TheProject
-- [WebContent]
-- -- [WEB-INF]
-- -- index.jsp
-- -- [IMAGES]
-- -- -- image.jpg
-- [Source Packages]
----ImageHandlerServlet.java
In ImageHandlerServlet.java, I am using the following code
String path = getServletContext().getRealPath("/Images");
Which gives following path. D:\BH\workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\proj\Images
URL path2 =getServletContext().getResource("/image.jpg");
which returns null.
InputStream stream = getServletContext().getResourceAsStream("/image.jpg");
which returns null;
I want to read the file from WebContent/IMAGES/ instead of WEB-INF. Using real path it can be achieved. What should I do? I consulted following related posts.
Upvotes: 1
Views: 11155
Reputation: 1108587
The ServletContext#getResource()
and getResourceAsStream()
take a path relative to web content. From that point on, you've the image actually in /IMAGES/image.jpg
.
InputStream stream = getServletContext().getResourceAsStream("/IMAGES/image.jpg");
Noted should be that you should never use getRealPath()
nor File
API on webcontent resources.
Also noted should be that using a servlet is unnecessary when you intend to serve out images. When putting outside the private /WEB-INF
folder, they're this way just publicly accessible as below in JSP:
<img src="${pageContext.request.contextPath}/IMAGES/image.jpg" />
Or in Facelets:
<img src="#{request.contextPath}/IMAGES/image.jpg" />
Or with JSF:
<h:graphicImage value="/IMAGES/image.jpg" />
Upvotes: 4