Vinod
Vinod

Reputation: 2311

Unable to load the images in the jsp page

I have created a simple jsp page in the spring mvc project. But i am unable to load the images from the image folder. I tried with Real path and Context path still I am unable to load the images in to the jsp file.

Real path:

<%
 String realPath = application.getRealPath("/");
%>

 <img src="<%=realPath%>images\logo.png" alt="student" title="student">

Context Path:

<%
 String contextPath = request.getContextPath();
%>
 <img src="<%=realPath%>images\logo.png" alt="student" title="student">

My project folder struture looks like

enter image description here

Did I miss something? Do I need to make any configurations in the web.xml?

Any suggestions?

Upvotes: 0

Views: 2553

Answers (2)

Andreas
Andreas

Reputation: 159096

  1. You cannot use real path, because the browser will not be on the same machine as the webapp!!
  2. You cannot use \, because URLs must use /.
  3. Don't use Java code in JSP, especially when EL variables are there to be used.
  4. You are missing a /. Quoting javadoc of getContextPath():

    The path starts with a "/" character but does not end with a "/" character.

This is how to do it:

<img src="${pageContext.request.contextPath}/images/logo.png" alt="student" title="student">

Upvotes: 1

tcharaf
tcharaf

Reputation: 630

You must configure your static resources like images, js and css files like that:

<mvc:resources mapping="/images/**" location="/images/"/>

In the above example, any requests from this url pattern /images/**, Spring will look for the resources from the /images folder.

Upvotes: 1

Related Questions