優點
urlrewriter簡介:url rewrite將我們的動態網頁地址轉化爲靜態的地址,如html、shtml,還可以隱藏網頁的真正路徑,比如:有時候需要將xxx.com/news/ type1/001.jsp 轉化成顯示路徑爲xxx.com/news_type1_001.jsp。
【第一步】下載jar包
在http://tuckey.org/urlrewrite/#download下載最新的jar文件,當前最新的是Beat3.2我下載的是urlrewritefilter-2.6.zip。解壓得到urlrewrite-2.6.0.jar 和 urlrewrite.xml
【第二步】
urlrewrite-.jar複製到項目的WebRoot/WEB-INF/lib/目錄下,然後編譯。【第三步】
把urlrewrite.xml複製到項目的WebRoot/WEB-INF/目錄下
【第四步】
在web.xml文件中加入以下:
1 <!-- 動態地址靜態化 -->
<!-- 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>DEBUG</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
【第五步】
1.3 如何靜態化
到這裏相關的配置已經完成,下面看如何把動態地址靜態化:
(1)普通url靜態化
例如:要把http://localhost/prjtest/user/list.jsp轉換成http://localhost/prjtest/user/list.html
這種是最簡單的,當一個servlet跳轉到list.jsp頁面列出user列表時,在urlrewrite.xml中這樣配置:
1 <rule>
2 <from>^/user/list.html</from>
3 <to>/user/list.jsp</to>
4 </rule>
當請求/user/list.html這個頁面時,實際上相當於請求/user/list.jsp頁面
在servlet的跳轉要這樣寫:
response.sendRedirect("./user/list.html");
(2)帶參數的url靜態化
例如:要把http://localhost/prjtest/user/view.jsp?cid=1&cname=admin轉換成
http://localhost/prjtest/user/view/1_admin.html
在urlrewrite.xml中這樣配置:
1 <rule>
2 <from>^/user/view/([0-9]+)_([a-z]+).html$</from>
3 <to>/user/view.jsp?cid=$1&cname=$2</to>
4 </rule>
當請求/user/view/1_admin.html這個頁面時,實際上相當於請求/user/list.jsp?cid=1&cname=admin頁面,在servlet的跳轉要這樣寫(cid,cname爲變量):
response.sendRedirect("./user/view/"+ cid +"_"+ cname +".html");
注意:當傳多個參數時,&應該寫成&