因爲Spring MVC的web.xml文件中關於DispatcherServlet攔截url的配置爲"/",攔截了全部的請求,同時*.js,*.jpg等靜態資源也被攔截了,致使運行時跳轉後的頁面沒法加載圖片資源,以下圖所示。css
web.xml:html
1 <!-- 配置DispatcherServlet所要攔截的url -->
2 <servlet-mapping>
3 <servlet-name>springmvc</servlet-name>
4 <url-pattern>/</url-pattern>
5 </servlet-mapping>
loginSucc.jsp:java
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>Spring MVC歡迎頁面</title>
8 </head>
9 <body>
10 返回信息:${msg} 11 <!-- 靜態資源jpg -->
12 <img alt="靜態資源圖片" src="../image/20160726.jpg">
13 </body>
14 </html>
需求:正常加載出圖片資源。web
只須要修改springmvc.xml: spring
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:mvc="http://www.springframework.org/schema/mvc"
5 xmlns:p="http://www.springframework.org/schema/p"
6 xmlns:context="http://www.springframework.org/schema/context"
7 xmlns:aop="http://www.springframework.org/schema/aop"
8 xmlns:tx="http://www.springframework.org/schema/tx"
9 xsi:schemaLocation="http://www.springframework.org/schema/beans 10 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 11 http://www.springframework.org/schema/context 12 http://www.springframework.org/schema/context/spring-context-4.0.xsd 13 http://www.springframework.org/schema/aop 14 http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 15 http://www.springframework.org/schema/tx 16 http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 17 http://www.springframework.org/schema/mvc 18 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 19 http://www.springframework.org/schema/context 20 http://www.springframework.org/schema/context/spring-context-4.0.xsd">
21
22 <!-- 自動註冊組件 -->
23 <mvc:annotation-driven/>
24
25 <!-- 經過掃描將帶有@Controller註解的類交由spring容器管理並維護 -->
26 <context:component-scan base-package="com.pers"/>
27
28 <!-- 配置視圖解析器 若是不配置ViewResolver,Spring MVC默認使用org.springframework.web.servlet.view.InternalResourceViewResolver做爲 29 ViewResolver,並且prefix和suffix都爲空 -->
30 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
31 <property name="prefix" value="/WEB-INF/jsp/"></property>
32 <property name="suffix" value=".jsp"></property>
33 </bean>
34
35 <!-- 訪問靜態資源 -->
36 <mvc:resources location="/image" mapping="/**"/>
37
38 </beans>
其中,在原來的基礎上添加的配置有:瀏覽器
a) 22~23行(用於自動註冊組件)spring-mvc
b) 35~36行(用於訪問靜態資源,按照這個格式也能夠添加js,css或其餘須要加載的靜態資源,網上有別的寫法:<mvc:resources location="/image/" mapping="/image/**">也能夠正常加載出image文件夾下的圖片)。tomcat
3.1. 在WEB-INF下建立名爲image的文件夾,將圖片拷貝到這個文件夾中,最後項目結構以下圖:
mvc
3.2. 啓動tomcat,在瀏覽器地址欄輸入url:http://localhost:8080/SpringMVC/index.jspapp
點擊"登陸"按鈕,頁面跳轉,圖片加載成功:
網上有資料稱還有別的兩種方法,這裏再也不贅述。