您的位置:首页 > 编程语言 > Java开发

Spring 静态资源配置

2016-03-09 16:15 176 查看

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[/code] 
最后得到

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">[/code] 
3、在配置文件中,加入以下配置

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


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

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

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


方法二、避免硬编码引用

href="<c:url value="/css/bootstrap.min.css" />"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: