2

I am using eclipse when I give relative path from my JSP file image does not appear. but when I use absolute path to my image then it work only in Eclipse' Internal browser but still does not works on other browsers Firfox, IE etc.

1 Answers1

8

Apparently the relative path was plain wrong.

You need to realize that the <img src> should refer to a public URL, not to the local disk file system of the webserver. It's namely the webbrowser who needs to load the image, not the webserver itself. If this public URL is relative, then it is resolved relative to the current request URL, the one which you see in the browser's address bar. It's not resolved relative to the location of the JSP in the local disk file system.

Imagine that you're opening the JSP page on this URL

http://localhost:8080/contextname/some.jsp

and that the image is in its raw form accessible on this URL

http://localhost:8080/contextname/images/some.png

then the image needs to be referenced in the JSP as follows

<img src="images/some.png" />

But if the JSP is openedby this URL

http://localhost:8080/contextname/somefolder/some.jsp

then the image needs to be referenced in the JSP as follows

<img src="../images/some.png" />

To avoid fiddling with relative paths everytime, you can also just use a domain-relative URL. You can do this by prepending the image URL with the context path:

<img src="${pageContext.request.contextPath}/images/some.png" />

this will end up in the generated HTML as follows (rightclick JSP in browser, View Source)

<img src="/contextname/images/some.png" />

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555