首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring MVC 靜態資源配置完全指南:mvc:resources、default-servlet-handler 與避坑清單

     編輯:Java 綜合教學

為什麼需要專門配置靜態資源?

DispatcherServlet 映射為 / 時會攔截所有請求(含 .css/.js/.png),導致:

  • 靜態資源走 Controller 處理流程,效能低
  • 找不到對應 @RequestMapping 拋 404

Spring 3.0.4+ 標準方案:mvc:resources

1. 命名空間宣告

<beans xmlns="https://www.springframework.org/schema/beans"
       xmlns:mvc="https://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
         https://www.springframework.org/schema/mvc
         https://www.springframework.org/schema/mvc/spring-mvc.xsd">

2. 核心配置

<!-- 必須:啟用 @RequestMapping 等註解驅動 -->
<mvc:annotation-driven/>

<!-- 靜態資源映射:** 表示遞歸所有子目錄 -->
<mvc:resources mapping="/css/**" location="/bootstrap-3.3.5-dist/css/"/>
<mvc:resources mapping="/js/**" location="/bootstrap-3.3.5-dist/js/"/>
<mvc:resources mapping="/images/**" location="/img/"/>
<mvc:resources mapping="/fonts/**" location="/fonts/"/>

<!-- 必須:讓容器預設 Servlet 處理靜態資源,繞過 DispatcherServlet -->
<mvc:default-servlet-handler/>

3. 路徑對照表

瀏覽器請求映射規則實際磁碟路徑
/css/bootstrap.min.css/css/** → /bootstrap-3.3.5-dist/css/webapp/bootstrap-3.3.5-dist/css/bootstrap.min.css
/js/app/main.js/js/** → /bootstrap-3.3.5-dist/js/webapp/bootstrap-3.3.5-dist/js/app/main.js

JSP 頁面引用最佳實踐

方案一:硬編碼專案名(不推薦)

<link href="/MyWeb/css/bootstrap.min.css" rel="stylesheet">

方案二:JSTL c:url 動態生成(推薦)

<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<link href="<c:url value='/css/bootstrap.min.css' />" rel="stylesheet">
<script src="<c:url value='/js/app/main.js' />"></script>

優點:自動補上 contextPath,專案重命名/部署到根路徑皆無需改碼。

Spring Boot 時代的簡化配置

# application.yml
spring:
  mvc:
    static-path-pattern: /static/**
  resources:
    static-locations: classpath:/static/,classpath:/public/,classpath:/resources/,classpath:/META-INF/resources/

預設將 src/main/resources/static 映射為 /static/**,零配置即用。

常見坑點排查清單

現象可能原因解決
靜態資源 404缺少 mvc:default-servlet-handler加上該標籤,或確認容器 web.xml 有 DefaultServlet
Controller 失效mvc:resources 映射順序搶先確保 mvc:annotation-driven 在前,資源映射具體路徑優先
CSS/JS 相對路徑圖片 404CSS 內 url(../img/x.png) 相對編譯後路徑使用 url(/images/x.png) 絕對路徑或配置 mvc:resources 映射 images
快取不更新瀏覽器/代理快取啟用 ResourceUrlEncodingFilter + 版本號 /css/app.css?v=20240118
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved