將動態 URL(如 `/article.do?id=123`)重寫為靜態風格 URL(如 `/article-123.html`),**不改變後端處理邏輯**,僅在 Web 容器層面做 URL 映射。好處:SEO 友好、隱藏技術細節、便於遷移。
Java 生態標準解決方案,純 Servlet Filter 實現,無侵入業務代碼,支援正則、條件、轉發/重導向多種模式。
<dependency>
<groupId>org.tuckey</groupId>
<artifactId>urlrewritefilter</artifactId>
<version>4.0.4</version>
</dependency>
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
<init-param>
<param-name>confPath</param-name>
<param-value>/WEB-INF/urlrewrite.xml</param-value> <!-- 規則檔位置 -->
</init-param>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher> <!-- 支援 forward 後再次重寫 -->
</filter-mapping>
放置於 `
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 4.0//EN"
"https://www.tuckey.org/res/dtds/urlrewrite4.0.dtd">
<urlrewrite default-match-type="wildcard">
<!-- 範例 1:簡單映射 .html → .jsp -->
<rule>
<from>/article-*.html</from>
<to type="forward">/article.jsp?id=$1</to>
</rule>
<!-- 範例 2:REST 風格 /user/123/profile → /userProfile.jsp?uid=123 -->
<rule>
<from>/user/([0-9]+)/profile</from>
<to type="forward">/userProfile.jsp?uid=$1</to>
</rule>
<!-- 範例 3:帶條件:僅非靜態資源才重寫 -->
<rule>
<condition type="request-filename" operator="notequal">.*\.(css|js|png|jpg|gif|ico)$</condition>
<from>^/(.*)$</from>
<to type="forward">/$1</to> <!-- 透傳 -->
</rule>
<!-- 範例 4:外部重導向(地址列變化) -->
<rule>
<from>/old-page\.jsp</from>
<to type="redirect">%{context-path}/new-page.html</to>
</rule>
</urlrewrite>
| 元素/屬性 | 說明 |
|---|---|
<rule> | 單條規則,順序執行,首個匹配生效 |
<from> | 匹配模式,支援 wildcard (`*`) 或 regex(需 `default-match-type="regex"` 或單獨指定) |
<to type="forward|redirect|passthrough"> | forward:內部轉發(地址列不變);redirect:302 重導向;passthrough:不處理 |
$1, $2... | 反向引用 ` |
<condition> | 額外條件:type=header/parameter/attribute/request-filename 等,operator=equal/notequal/greater/less 等 |
<set> | 設定請求屬性/Header/參數供後續處理使用 |