chonglawr chonglawr - 7 months ago 130
Java Question

How can I load an image from my resources/images folder in spring mvc?

I am trying to load 2 images from my resources/images folder and display them on my index.jsp:

<img src="<c:url value='/resources/images/harry_potter.jpg'/>"/>
<img alt="Image" src="${pageContext.request.contextPath}/resources/images/harry_potter.jpg">

<img src="<c:url value='/resources/images/hp.jpg'/>"/>
<img alt="Image" src="${pageContext.request.contextPath}/resources/images/hp.jpg">


When I load the page images don't appear, instead there are image icons. As you've seen in my index.jsp, I've tried 2 different methods for loading an image

I have an application.xml page and a dispatcher-servlet page.xml

In each file I have tried putting this under the context:component-scan

<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/" />


but I still do not see my images on the index page. Does anyone know why this isn't showing

My File Structure for reference:

File Image View

File Image View

In my web.xml for reference:

<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>


Console for reference

Console Image View

Console Image View

Answer

Try this please, may work;)

Change

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

to

<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
Comments