bilalhaider
bilalhaider

Reputation: 181

Read the file from WebContent/IMAGES/ instead of WEB-INF

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.

  1. getresourceasstream-is-always-returning-null
  2. access-file-inside-webcontent-from-servlet
  3. java-tomcat-servletcontext-getresourceasstream-problems

Upvotes: 1

Views: 11155

Answers (1)

BalusC
BalusC

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" />

See also:

Upvotes: 4

Related Questions