項目搭建系列之四:SpringMVC框架下使用UrlRewrite實現地址重寫


  簡單記錄一下UrlRewrite實現地址重寫功能。

1、pom.xml

  在pom.xml增加配置UrlRewrite jar

<!-- URL Rewrite -->
<dependency>
    <groupId>org.tuckey</groupId>
    <artifactId>urlrewritefilter</artifactId>
    <version>4.0.4</version>
</dependency>

2、web.xml

  在web.xml文件中配置UrlRewriteFilter,這里可能要注意filter的加載順序。

  <!-- 開啟URLREWRITE監聽 -->
  <filter>
    <filter-name>UrlRewriteFilter</filter-name>
    <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
    <init-param>
      <param-name>logLevel</param-name>
      <param-value>WARN</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
  </filter-mapping>

3、urlrewrite.xml

  urlrewrite.xml 這個配置文件目前只能放在 WEB-INF 下。

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.2//EN" "\\urlrewrite3.2.dtd">
  
<urlrewrite>
  
  <rule>
    <note>重寫index.jsp成index.html</note>
    <note>example:/index.html</note>
    <from>/index.html</from>
    <to type="forward">/index.jsp</to>
  </rule>
  
  <rule>
    <note>將view根目錄下所有jsp資源重寫成/xxx.action</note>
    <note>example:/index.action</note>
    <from>/([A-Za-z0-9]+).action</from>
    <to type="forward">/view/$1.jsp</to>
  </rule>
  
  <rule>
    <note>forward(轉發模式)傳參</note>
    <note>example:/user/param/fancy/8080.do</note>
    <from>/user/([A-Za-z0-9]+)/([A-Za-z0-9]+)/([A-Za-z0-9]+).do</from>
    <to type="forward">/view/parameter/$1.jsp?username=$2&amp;password=$3</to>
  </rule>
  
  <rule>
    <note>redirect(重定向模式)傳參,to中寫絕對地址</note>
    <note>example:/admin/param/fancy/8080.do</note>
    <from>/admin/([A-Za-z0-9]+)/([A-Za-z0-9]+)/([A-Za-z0-9]+).do</from>
    <to type="redirect">/urlrewrite-maven-example/view/parameter/$1.jsp?username=$2&amp;password=$3</to>
  </rule>
  
</urlrewrite>

4、注釋

第一個rule:訪問 /index.html,實際上是訪問了 /index.jsp

第二個rule:訪問 /xx.action , 實際上是訪問了 view 目錄下的 xx.jsp

第三個rule:訪問 /user/xx/yy/zz.do , 實際上是訪問了 view 目錄下的 parameter 目錄下的 xx.jsp?username=yy&password=zz

第四個rule:跟第三個其實是一樣的,但是由於是重定向模式,所以地址欄就會顯示真的是地址

<rule>:自定義匹配規則

<note>:注釋,解釋標簽

<from>:定義具體的匹配規則

<to>:匹配成功后的目標地址

<to type="">:type的值有兩個,一個是 forward (轉發,參數不丟失),一個是 redirect (重定向,地址欄顯示的地址就是目標真實地址)

$1:匹配中的第一個正則表達式的字符串的值,$2,$3,$4....也是如此

&amp; 是 & 的實體名,代表的就是 &


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM