在Spring MVC中不显示图像


问题内容

我知道这个问题已经被问过很多次了,但是我无法弄清楚问题出在哪里。我在src / main / webapp文件夹(这是一个Maven
Web项目)下有images文件夹。我在src / main / webapp / WEBINF / views文件夹中有index.jsp。

我正在尝试访问图像和其他资源,例如css和js,如下所示:

<img src="/images/left_arrow.png" alt="" />

但是图像无法显示。

这是web.xml文件

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">

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

<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

这是WEB-INF / mvc-dispatcher-servlet.xml文件

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.ravi.WebApp" />

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/views/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

</beans>

这是Controller包com.ravi.WebApp;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

@RequestMapping("/")
public String printWelcome(Model model) {
    return "index";

}

}

问题答案:

尝试将以下资源声明添加到您的Spring配置中:

<!-- Handles HTTP GET requests for /images/** by efficiently serving up static resources in the ${webappRoot}/images directory -->
<resources mapping="/images/**" location="/images/" />

另外,更常见的是,有一个resources包含所有资源(图像,css,js等)的文件夹,该文件夹按子目录划分。

您的配置将如下所示:

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

您的资源将被引用如下:

<link rel="stylesheet" type="text/css" href="<c:url value="/resources/css/screen.css" />" />
<script type="text/javascript" src="<c:url value="/resources/js/jquery-1.6.4.min.js" />"></script>
<img src="<c:url value="/resources/images/left_arrow.png" />" alt="" />