You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring MVC 3.1 resources目录下CSS文件无法加载问题排查

Spring MVC静态资源CSS加载失败修复方案

问题根源

静态资源无法加载的核心原因是Spring MVC请求拦截规则未对静态资源放行,原有配置存在以下典型问题:

  • 仅配置<resources>路径映射规则,但未配套开启MVC注解驱动、配置默认Servlet处理器,导致静态资源映射规则未实际生效。所有CSS类静态资源请求都被DispatcherServlet拦截,找不到对应控制器映射时直接返回404。
  • 部分老项目Spring配置文件头缺失mvc命名空间声明和对应xsd地址,会导致<resources>标签无法被Spring解析,配置完全不生效。
  • 若web.xml中DispatcherServlet的url-pattern配置为/*而非/,会强制拦截所有请求(包括静态资源、JSP),同样会导致资源加载失败。

修复步骤

  1. 打开Spring MVC核心配置文件(通常命名为spring-mvc.xml、servlet-context.xml),确认beans根节点包含mvc命名空间相关声明,参考配置如下:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 原有业务配置保留即可 -->
</beans>
  1. 在原有静态资源映射配置的同级位置,添加如下两行配置:
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<resources mapping="/resources/**" location="/resources/" />

配置说明:<mvc:default-servlet-handler />会注册默认请求处理器,所有未被Controller匹配的请求都会转交给Web容器(如Tomcat)的默认Servlet处理,静态资源不会再被Spring MVC拦截。

  1. 检查web.xml中DispatcherServlet的映射配置,确保url-pattern配置为/而非/*:
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
  1. 重启应用服务器,清空浏览器缓存后,先直接访问CSS文件全路径确认可正常返回文件内容,再刷新页面即可看到Bootstrap样式正常加载。

原有JSP中通过JSTL引入CSS的写法正确,CSS文件存放路径符合配置规则,无需调整。


内容的提问来源于stack exchange,提问作者Hien Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 23:33:21