我们为什么要使用URLRewrite重写url技术呢,在网上搜了一下,有篇文章说是有主要三个原因
1、满足搜索引擎的要求
2、隐藏技术实现,提高网站的移植性
3、满足美感的要求
首页,访问其官网:我下载的是最新的目前还处于Beta版的urlrewritefilter-3.2.0,下载后将其中的urlrewrite-3.2.0.jar扔到需使用此功能项目的lib目录中去
创建一个web工程,结构目录文件如下(注意工程中我们需要使用到urlrewrite.jar包)
其次,在web.xml中加入如下配置:
<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>
其实,urlrewrite其实就是个过虑器,它将会过虑用户的所有请求,符合规则的便对其进行重定向,具体的配置参数的使用方法见官方文档:
配置好web.xml后将下载的urlrewritefilter-3.2.0中的urlrewrite.xml配置文件放在WEB-INF目录下,这样在使用urlrewritefilter时它便自动到该目录下读取相关的配置了
Url 重写的主要内容就是在web-inf中要编写urlrewrite.xml文件,其实内容很简单。
本例中的xml编写的内容如下
我们先来分析一下rule规则
<rule>
<from>^/page/(.*)$</from>
<to>/page/$1.jsp</to>
</rule>
from代表你在访问网站的时候,浏览器地址栏中显示的URL
to代表将浏览器中显示的URL转换后的地址,也就是你网站中真正访问的URL
以之前我们建立的web项目为列 (这里只是简略的做了一下转换,既不显示路径后缀)
我们访问 http://localhost:8080/URLRewrite/page/first
而实际我们访问的是http://localhost:8080/URLRewrite/page/first.jsp
我们再来说说<outbound-rule>,outbond-rule在网上的说的不多。其实RULRewrite本身的说明已经写的很清楚了。
Theoutbound-rule specifies that when response.encodeURL is called (if you are using JSTL c:url) theurl /rewrite-status will be rewritten to /test/status/. The above rule and thisoutbound-rule means that end users should never see the url /rewrite-status only /test/status/ both inthier location bar and in hyperlinks
在使用response.encodeURL或是c:url的时候,路径rewrite-status将被重写成 /test/status/
以上的rule和outbound-rule将使最终用户在他们的地址栏或链接中都不会看到/rewrite-status而只能看到重写后的/test/status/ |
其它主要是用于解决我们在页面中显示链接的问题,如我们在页面上有一个链接
页面代码如下
我们对链接使用respone.encodeURL进行编码,用于跳转到第二页。
但是我们注意我们页面浏览器的状态栏。它已经根据我们的规则进行了转换。
但是这里我们一定要注意一个问题 使用<outbound-rule>转换过来的URL,一定要符合 <rule> <from>^/page/(.*)$</from> <to>/page/$1.jsp</to> </rule>
也就是说,我们的encodeURL路径为../second.jsp?para=first 首先根据<outbound-rule>转换为我们在状态栏中看到的地址 http://localhost:8080/URLRewrite/page/second,然后再根据<rule>的根据,将其路径转换为http://localhost:8080/URLRewrite/page/second.jsp来访问我们站点中真正的路径。
|
这样我们就可以全部将我们的真实路径重写掉。对外只暴露重写后的地址。