Spring 静态资源配置

ShineJaie 原创整理,转载请注明出处。

一、为何要配置静态资源

1、在配置 Spring 的时候,我们配置的拦截是"/",即任何文件都会经 Spring 拦截处理。

2、实际上静态资源,如 css、js、图片的引用是不需要 Spring 处理的。

二、解决方案

Spring 3.0.4 之后引入了 mvc:resoures 配置,可以声明哪些资源不需要 Spring 来处理。

1、在 spring 配置文件(spring-servlet,xml)的顶部 xmlns 加上 schema 描述

xmlns:mvc="http://www.springframework.org/schema/mvc"

2、在 xsi:schemaLocation 中加上

http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd

最后得到

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:context="http://www.springframework.org/schema/context"
 4        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5        xmlns:mvc="http://www.springframework.org/schema/mvc"
 6        xsi:schemaLocation="http://www.springframework.org/schema/beans
 7         http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
 8         http://www.springframework.org/schema/context
 9         http://www.springframework.org/schema/context/spring-context-4.1.xsd
10         http://www.springframework.org/schema/mvc
11         http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

3、在配置文件中,加入以下配置

1 <!-- 配置 springMVC 不拦截的静态资源 -->
2 <!-- 必须加,否则 RequestMapping 失效 -->
3 <mvc:annotation-driven/>
4 <!-- css 下所有文件都映射到 /bootstrap/css/ (*: 只处理文件夹下一级; **: 文件夹下多级) -->
5 <mvc:resources mapping="/css/**" location="/bootstrap-3.3.5-dist/css/"/>
6 <mvc:resources mapping="/js/**" location="/bootstrap-3.3.5-dist/js/"/>
7 <!-- 表示上述配置的 css 文件不属 viewResolver 解析 -->
8 <mvc:default-servlet-handler/>

三、jsp 页面静态资源访问方法

方法一、根据项目名采用硬编码引用

href="/MyWeb/css/bootstrap.min.css"

方法二、避免硬编码引用

href="<c:url value="/css/bootstrap.min.css" />"



原文地址:https://www.cnblogs.com/shinejaie/p/5258630.html