Spring 靜態資源配置,spring靜態資源配置

來源:互聯網
上載者:User

Spring 靜態資源配置,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/mvchttp://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.xsd10         http://www.springframework.org/schema/mvc11         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" />"



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.