一. 问题及需求
由于Spring MVC的web.xml文件中关于DispatcherServlet拦截url的配置为"/",拦截了所有的请求,同时*.js,*.jpg等静态资源也被拦截了,导致运行时跳转后的页面无法加载图片资源,如下图所示。
web.xml:
<!-- 配置DispatcherServlet所要拦截的url -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
loginSucc.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring MVC欢迎页面</title>
</head>
<body>
返回信息:${msg}
<!-- 静态资源jpg -->
<img alt="静态资源图片" src="../image/20160726.jpg">
</body>
</html>
需求:正常加载出图片资源。
二. 解决方案
只需要修改springmvc.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 自动注册组件 -->
<mvc:annotation-driven/> <!-- 通过扫描将带有@Controller注解的类交由spring容器管理并维护 -->
<context:component-scan base-package="com.pers"/> <!-- 配置视图解析器 如果不配置ViewResolver,Spring MVC默认使用org.springframework.web.servlet.view.InternalResourceViewResolver作为
ViewResolver,而且prefix和suffix都为空 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean> <!-- 访问静态资源 -->
<mvc:resources location="/image" mapping="/**"/> </beans>
其中,在原来的基础上添加的配置有:
a) 22~23行(用于自动注册组件)
b) 35~36行(用于访问静态资源,按照这个格式也可以添加js,css或其他需要加载的静态资源,网上有别的写法:<mvc:resources location="/image/" mapping="/image/**">也可以正常加载出image文件夹下的图片)。
三. 测试
3.1. 在WEB-INF下创建名为image的文件夹,将图片拷贝到这个文件夹中,最后项目结构如下图:
3.2. 启动tomcat,在浏览器地址栏输入url:http://localhost:8080/SpringMVC/index.jsp
点击"登录"按钮,页面跳转,图片加载成功:
四. 总结
网上有资料称还有别的两种方法,这里不再赘述。