gnreddy
gnreddy

Reputation: 2503

How to access the images from jsp?

I am using Spring MVC 3.0.

I have to load the images which exist in the folder "images" parallel to the WEB-INFdirectory.

I have the jsp files in WEB-INF/jsp folder.

The folder structure is:

-app
--images
--WEB-INF
---jsp
---classes
...

In web.xml the url mapping for DispatcherServlet is some thing like

<servlet-mapping>
    <servlet-name>test</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Now in JSP if I load the jsp in the following way:

<img src="<%=request.getContextPath()%>/images/calogo.jpg" />

Its now working as DispatcherServlet is intercepting it I guess.

Upvotes: 0

Views: 3014

Answers (2)

Grzegorz Grzybek
Grzegorz Grzybek

Reputation: 6237

If you map / to DispatcherServlet, be sure to enable default servlet handler in Spring's config:

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />

<!-- add this to make Spring properly handle resources (e.g., images) -->
<mvc:default-servlet-handler />

Also, do not use <%... syntax use JSTL:

<img src="<c:url value="/images/calogo.jpg" />" />

(or better - do not use JSP at all, use e.g. ThymeLeaf)

Upvotes: 0

Japan Trivedi
Japan Trivedi

Reputation: 4483

Yes you are right. Your dispatcher is intercepting your request to display the images.

According to me when you try to access the image in your jsp file it will give you 404 error.

You need to include the following line of code in your servlet.xml file.

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

And then everything will work.

Hope this helps you.

Cheers.

Upvotes: 1

Related Questions