Spring MVC DispatcherServlet 默認映射 / 會攔截所有請求,導致靜態資源(JS、CSS、圖片、HTML)進入控制器層報 404。Spring 3.0+ 提供 <mvc:resources> 標籤將靜態目錄映射到默認靜態資源處理器,繞過控制器。
<mvc:resources location="/html/" mapping="/html/**"/> <mvc:resources location="/back_css/" mapping="/back_css/**"/> <mvc:resources location="/back_js/" mapping="/back_js/**"/> <mvc:resources location="/back_img/" mapping="/back_img/**"/> <mvc:resources location="/back_other/" mapping="/back_other/**"/> <mvc:resources location="/layer/" mapping="/layer/**"/> <mvc:resources location="/laypage/" mapping="/laypage/**"/>
location:靜態資源在 WAR 包中的物理路徑(相對 Web 根目錄),必須以 / 結尾。mapping:對外暴露的 URL 模式,** 表示遞歸所有子路徑。<mvc:resources mapping="/static/**" location="/static/, /public/, /assets/"/>
<mvc:resources mapping="/static/**" location="/static/" cache-period="31536000"/> <!-- 一年緩存,配合版本號或文件指紋實現長期緩存 -->
<mvc:resources mapping="/static/**" location="/static/">
<mvc:resource-chain resource-cache="true">
<mvc:resolvers>
<mvc:version-resolver>
<mvc:content-version-strategy /> <!-- 基於內容 MD5 生成版本號 -->
</mvc:version-resolver>
</mvc:resolvers>
</mvc:resource-chain>
</mvc:resources>
<mvc:resources> 註冊 ResourceHttpRequestHandler,Spring 在 DispatcherServlet 的 HandlerMapping 鏈中優先匹配靜態資源路徑,命中則直接輸出文件流,不進入 Controller。若未配置,請求落入 DefaultAnnotationHandlerMapping 尋找 @RequestMapping,找不到拋 404。
location 路徑寫錯(如漏掉前導 / 或結尾 /)。mapping 與 location 不對應(如 mapping /css/** 但 location /static/css/)。WEB-INF 下(外部不可直接訪問),需放在 Web 根目錄或 src/main/webapp。