Spring 靜態資源配置

ShineJaie 原創整理,轉載請註明出處。

1、爲什麼要配置靜態資源

一、在配置 Spring 的時候,咱們配置的攔截是"/",即任何文件都會經 Spring 攔截處理。css

二、實際上靜態資源,如 css、js、圖片的引用是不須要 Spring 處理的。html

2、解決方案

Spring 3.0.4 以後引入了 mvc:resoures 配置,能夠聲明哪些資源不須要 Spring 來處理。spring

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

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

二、在 xsi:schemaLocation 中加上spring-mvc

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

最後獲得mvc

 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">

三、在配置文件中,加入如下配置app

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/>

3、jsp 頁面靜態資源訪問方法

方法1、根據項目名採用硬編碼引用jsp

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

方法2、避免硬編碼引用編碼

href="<c:url value="/css/bootstrap.min.css" />"
相關文章
相關標籤/搜索