配置 `
<!-- web.xml -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern> <!-- 必須是 /,不能是 /* -->
</servlet-mapping>
❌ `/*` 會攔截所有請求包括靜態資源、JSP、轉發,**導致靜態資源處理器無法生效**。
✅ `/` 只攔截未匹配到靜態資源的請求,**讓容器默認 Servlet 處理靜態資源**,或由 Spring `ResourceHttpRequestHandler` 處理。
# logback.xml / log4j2.xml
<logger name="org.springframework.web.servlet.resource" level="DEBUG" />
<logger name="org.springframework.web.servlet.handler" level="DEBUG" />
啟動日志關鍵信息:
Mapped URL path [/static/**] onto handler of type [ResourceHttpRequestHandler]
若無此日志,說明 `
@Controller
@RequestMapping("/") // ❌ 根路徑通配,攔截所有含 /static/ 的請求
public class BadController { ... }
@Controller
@RequestMapping("/api") // ✅ 明確業務前綴
public class GoodController { ... }
**原則**:Controller 映射**盡量具體**,避免 `@RequestMapping("/")` 或 `@RequestMapping("/**")` 搶佔靜態資源路徑。
| location 值 | 物理位置 (Maven 標準) | 訪問 URL |
|---|---|---|
| `/static/**` | `src/main/resources/static/` | `/static/js/app.js` |
| `/public/**` | `src/main/resources/public/` | `/public/css/style.css` |
| `classpath:/META-INF/resources/` | Jar 包內 / WebJars | `/webjars/jquery/...` |
⚠️ `location` 必須以 `/` 結尾表示目錄,`mapping` 以 `/**` 結尾表示遞歸匹配。
# application.yml
spring:
mvc:
static-path-pattern: /static/** # 默認 /**
resources:
static-locations: classpath:/static/,classpath:/public/ # 默認多個
cache:
period: 3600
cachecontrol:
max-age: 3600
Spring Boot 2.x+ **不需手寫 `
靜態資源 404 核心三大塊:**DispatcherServlet 映射 `/`**、**ResourceHandler 註冊生效**、**Controller 不搶佔路徑**。Spring Boot 專案優先用屬性配置,傳統 XML 專案核對 `url-pattern` 與 `