頁面引入 /resources/easyui/... 等靜態資源全部報 **404 Not Found**,雖然文件確實存在於 WebContent/resources 目錄下。
SpringMVC 的 DispatcherServlet 默認攔截所有請求(包括靜態資源),**未配置靜態資源映射**時,會嘗試尋找對應 Controller,找不到拋 404。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:mvc="https://www.springframework.org/schema/mvc"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 開啟註解驅動 -->
<mvc:annotation-driven />
<!-- 靜態資源映射:關鍵配置 -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:resources mapping="/static/**" location="/static/" />
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/images/**" location="/images/" />
<!-- 其他配置... -->
</beans>
spring:
mvc:
static-path-pattern: /resources/**
web:
resources:
static-locations: classpath:/resources/,classpath:/static/,classpath:/public/
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/")
.setCachePeriod(3600); // 緩存 1 小時
registry.addResourceHandler("/static/**")
.addResourceLocations("/static/");
}
}
<!-- 使用項目上下文路徑,避免相對路徑問題 -->
<%=request.getContextPath()%>/resources/easyui/themes/default/easyui.css
<!-- 或使用 JSTL core -->
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<link href="<c:url value='/resources/easyui/themes/default/easyui.css'/>" rel="stylesheet" />
<!-- JS -->
<script src="<c:url value='/resources/easyui/jquery.min.js'/>"></script>
WebContent/
├── resources/
│ ├── easyui/
│ │ ├── themes/default/easyui.css
│ │ ├── jquery.min.js
│ │ └── ...
│ ├── css/
│ ├── js/
│ └── images/
├── WEB-INF/
│ ├── web.xml
│ └── spring-mvc.xml
└── index.jsp
| 錯誤 | 後果 | 修正 |
|---|---|---|
location 缺少結尾 / | 路徑拼接錯誤 | location="/resources/" |
| mapping 與 location 不對應 | 找不到文件 | 保持一致:/resources/** → /resources/ |
未開啟 <mvc:annotation-driven/> | 靜態資源處理器未註冊 | 必須添加 |
| web.xml 中 DefaultServlet 未配置 | 容器默認 Servlet 不處理靜態資源 | Spring MVC 3.0+ 通常自動處理 |
https://localhost:8080/項目名/resources/easyui/jquery.min.jsapplication/javascript**核心動作**:在 Spring MVC 配置中添加 <mvc:resources mapping="/resources/**" location="/resources/" />,讓 DispatcherServlet 放行靜態資源請求交由容器默認 Servlet 處理。