Unable to load static contents (Images/JS) in web-application

只愿长相守 提交于 2019-12-25 19:03:07

问题


I'm working on an application and where I need to refer my application images and other things like js etc. now in my JSP files when I'm trying to load images using this path

<img src="static/media/images/logo.gif" alt="welcome" />

I saw the following error in the browser: unable to load the image

I even tried to refer the absolute path

<img src="/static/media/images/logo.gif" alt="welcome" />

but still no luck at all. Finally when I appended my project name it started working. E.g if my web-application name is abc I used following thing

<img src="/abc/static/media/images/logo.gif" alt="welcome to donateblood.com" />

but that I'm sure not the right way to refer the images as this means change in web-application name will lead me to change each and every URL of image which is not feasible at all. The images which has been mentioned inside the css file are working perfectly fine. can anyone guide me the proper way to refer the images.

Additional information: I'm using eclipse as my IDE and Tomcat as the container along with it is a Java EE standard web-application


回答1:


static/media/images/logo.gif

is a relative path. If you're on the page http://localhost/myWebApp/foo/bar.html, it will resolve to

http://localhost/myWebApp/foo/static/media/images/logo.gif

/static/media/images/logo.gif

is a path which is absolute to the web server.Wherever you are, it resolves to

http://localhost/static/media/images/logo.gif

You thus need to prepend the web app's context path to the absolute path. Use

<img src="${pageContext.request.contextPath}/static/media/images/logo.gif" alt="welcome" />

or

<img src="<c:url value='/static/media/images/logo.gif'/>" alt="welcome" />

as you should do for all the URLs in the webapp.



来源:https://stackoverflow.com/questions/8509056/unable-to-load-static-contents-images-js-in-web-application

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