Url Rewrite 代替apache实现jsp页面伪静态化
Url Rewrite Filter 是一个基于java的url rewirte开源项目,功能类似Apache中的rewrite模块。其实,Url Rewrite让apache来负责才是最好的选择,因为mod_rewrite已经很成熟了,功能或者效率上都更好用,apache已足以使urlrewrite的功能透明了,对于多个应用使用起来更方便。这篇文章介绍的urlrewrite filter只是给那些不打算使用apache的应用提供了另外一种选择。 一、主要功能 a) 实现url地址的伪静态化 例如可以把http://localhost:8080/myindex.do?method=listIndex&user=ezplus的请求重定向或转发到http://localhost:8080/blog/ezplus,这样做就避免了url中出现?&之类的符号,而且页面伪静态化之后也增加了被搜索引擎找到的概率。 b) 根据配置文件自动转化页面上的连接 在写页面的时候程序员不用关心在页面中出现的url地址将被如何伪静态化,例如,程序员还是可以在写页面的时候使用http://localhost:8080/myindex.do?method=listIndex&user=ezplus,通过在urlrewrite.xml中配置<outbound-rule></outbound-rule>,既可以实现页面url地址自动转化为伪静态化后的地址,用户在查看页面源码的时候原http://localhost:8080/blog/ezplus将被自动替换为http://localhost:8080/blog/ezplus 二、安装使用 1.下载地址:http://tuckey.org/urlrewrite/#download 下载的文件(Binary的)结构简单:urlrewrite.xml和lib文件夹下的一个.jar
2.jar文件放入项目的lib库中,urlrewrite.xml和web.xml放在一块。修改web.xml,添加以下配置: <filter> <filter-name>UrlRewriteFilter</filter-name> <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class> </filter> <filter-mapping> <filter-name>UrlRewriteFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
我觉得/*这样的通配,并不符合我的预期,我只想对部分路径进行URL的重写,/*可能会造成我想象不到的或者是许微不足道的性能浪费.我把它改成了我需要的: <filter-mapping> <filter-name>UrlRewriteFilter</filter-name> <url-pattern>/member/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>UrlRewriteFilter</filter-name> <url-pattern>/article/*</url-pattern> </filter-mapping> 等...
3.urlrewriter.xml的配置 先提一下urlrewriter.xml中原有的几个例子: <rule> <from>/some/old/page.html</from> <to type="redirect">/very/new/page.html</to> </rule> /**从一个文件到另一个文件的转发 如果不使用正则表达式,这样的配置真是把简单的问题复杂化了**/ <rule> <from>/some/olddir/(.*)</from> <to type="redirect">/very/newdir/$1</to> </rule> /**重定向到一个目录 我觉得实际应用中可能用得不多**/ <rule> <from>/products/([0-9]+)</from> <to>/products/index.jsp?product_id=$1</to> </rule> /**这种是最常用的,通过正则对请求路径进行匹配,并把分组作为参数 ,实际转到到<to>的路径。<to type="redirect">和<to type="forword">有什么区别呢?<to type="redirect">是链接到外部的网站,<to type="forword">是链接到站内的实际地址。**/
说明一下,如果你在Filter配置中使用了所有路径通配符<url-pattern>/*</url-pattern> 在配置urlrewriter.xml中的<from>时,随便怎么写路径无所谓,但若象我一样使用了 <url-pattern>/memeber/*</url-pattern>,那么在<from>标签中也要写上/memeber/(你的正则分组) 以便在访问与<from>匹配的路径时,Filter能够执行
最后一点,不得不说,举个例子 <rule> <from>/member/(.*)</from> <to>/html/member.do?username=$1</to> </rule> <rule> <from>/article/(.*)</from> <to>/html/article.do?articleid=$1</to> </rule> <rule> <from>/member/article/(.*)</from> <to>/html/another/article.do?articleid=$1</to> </rule> 当你访问http://localhost/member/article/1111 会显示哪一个页面呢? 结果应该不是意想中的/html/another/article.do?articleid=1111. 我想大概是因为<from>中的路径,相当于filter中的<url-pattern>
|