---
title: "Spring MVC-Resources"
author: "Even521"
date: "2014-11-27T14:57:24Z"
tags: []
categories: ["编程语言"]
slug: "spring-mvc-resources"
draft: false
lastmod: "2014-11-27T15:02:05Z"
id: 2161265
url: "https://even521.iteye.com/blog/2161265"
---

Spring mvc项目中的web.xml配置的DispatcherServlet对应的url-pattern为"/"，即所有的URL请求都会经过Spring MVC的处理。但项目中往往会有许多静态文件，比如：图片文件，css样式文件，文本文件等。

我们没有必要对这些静态文件的访问都设置对应的URL，那样会造成大量重复性的劳动，以及维护上的复杂性。Spring MVC提供了一种机制，可以映射一种URL和一个location，此URL后面接的静态文件，对应着location目录下对应的静态文件。此配置为：

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

注意：处理HTTP GET请求/resources/ * \*通过有效地服务于静态资源在$ { webappRoot } /resources/目录中；

resources/ \** 两个星号代表resources下的所有子包。

servlet-context.xml:

```
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory -->
	<resources mapping="/resources/**" location="/resources/" />
	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
<!-- Imports user-defined @Controller beans that process client requests -->
	<beans:import resource="controllers.xml" />
	<task:annotation-driven />
```

resources目录结构：  
![](http://dl2.iteye.com/upload/attachment/0103/7164/a34cf217-91ac-3ef6-835d-9f62de8fe046.jpg)

访问这些静态文件：[http://localhost:9090/spring-mvc-showcase/resources/form.css](http://localhost:9090/spring-mvc-showcase/resources/form.css)

jsp页面效果图：  
![](http://dl2.iteye.com/upload/attachment/0103/7162/f6ee6d50-b504-3871-affc-d34aa071ab5b.jpg)  
 源码地址：[https://github.com/spring-projects/spring-mvc-showcase.git](https://github.com/spring-projects/spring-mvc-showcase.git)