使用URLRewrite 实现URL伪静态化

13年前

1.首先在http://tuckey.org/urlrewrite/#download下载urlrewirtefilter

2.解压所下载的文件,把urlrewrite-2.6.0.jar复制到项目的WebRoot/WEB-INF/lib/目录下

3.把urlrewrite.xml复制到项目的WebRoot/WEB-INF/目录下

4.在web.xml文件中加入filter

  1. <filter>  
  2. <filter-name>UrlRewriteFilter</filter-name>  
  3.    <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>  
  4.    <init-param>  
  5.     <param-name>logLevel</param-name>  
  6.     <param-value>WARN</param-value>  
  7.    </init-param>  
  8. </filter>  
  9. <filter-mapping>  
  10.    <filter-name>UrlRewriteFilter</filter-name>  
  11.    <url-pattern>/*</url-pattern>  
  12. </filter-mapping>  

 

5.配置urlrewrite.xml
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 type="redirect">/user/list.jsp</to>  
  4. </rule>  


当请求/user/list.html这个页面时,实际上相当于请求/user/list.jsp页面,在servlet的跳转要这样写:response.sendRedirect("./user/list.html");

2要把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 type="redirect">/user/view.jsp?cid=$1cname=$2</to>  
  4. </rule>  

6特别说明
为什么地址栏不变?
原因就在于浏览器显示的是最后被给定的URL。当一个URL被提交后,在某一个组件返回一个相应给浏览器之前,你的应用可能转发请求多次。所有这些都发生在服务器端,浏览器并不知道发生了什么事。当一个Http相应被放回时,它并没有包含地址信息,所以浏览器仅仅显示用来作为初始请求的地址。

要想让地址栏也变成静态化的URL,很简单,将<to type="redirect">改成<to type="forward">即可