近期学习了一个url定向的小框架urlrewritefilter,希望和大家分享。
1.简介
UrlRewriteFilter是一个用于改写URL的Web过滤器,类似于Apache的mod_rewrite。适用于任何Web应用服务器(如Resin,Orion,Tomcat等)。其典型应用就把动态URL静态化,便于搜索引擎爬虫抓取你的动态网页。
下载地址:(jar包和原代码都有)
http://tuckey.org/urlrewrite/#download
2.相关配置:首先要将下载的jar包导入到你的项目中,然后再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> <!--一下两项可以不写--> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping>
3.在和web.xml对等的位置建另一个名为urlrewrite.xml的xml文件
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 2.6//EN" "http://tuckey.org/res/dtds/urlrewrite2.6.dtd"> <urlrewrite> <!--主要就配置两项<rule>和<outbound-rule>里面具体的内容根据不同的逻辑编写不同的内容--> <rule> <from>/2th</from> <to type="redirect">%{context-path}/world.jsp</to> </rule> <rule match-type="regex"> <from>([a-z]+)/([a-z]+).html</from> <to type="redirect">%{context-path}/$1.jsp?country=$2</to> </rule> <outbound-rule> <from>world.jsp</from> <to>/2th</to> </outbound-rule> </urlrewrite>
配置文件规则:
urlrewirte 配置文件必须有一个urlrewrite根元素和包含至少一个rule元素 。
一个rule元素必须包含一个from 和一个to 元素,也可以包含0个以上的condition 元素和0个以上set 元素。
一个rule元素拦截用户的请求,from元素 是请求的url,to 元素是经过重写后的url 输出,下面是类似java 的重写内部实现。
3. 元素参数说明
<urlrewrite>元素
参数 | 取值 | 描述 |
default-match-type | regex(默认)、wildcard | 所有的rule和condition 元素都会用到该匹配方法 |
decode-using | header,utf8(默认)、null、iso-8859-1 等 | 当url 需要解码时request.getCharacterEncoding() 将被用到,如果为空,则为utf-8 |
use-query-string | false(默认)、true | 语句是否加到url的后面 |
use-context | false(默认)、true | 上下午路径是否要加到url 中 |
<rule>元素
参数 | 取值 | 描述 |
enable | true(默认)、false | 是否应用该rule |
match-type | regex(默认)、wildcard | 应用那种匹配规则 |
例子:
<!--请求输入: /world/usa/nyc 输出为 /world.jsp --> <!--应用java 的正则表达式--> <rule match-type="regex"> <from>^/world/([a-z]+)/([a-z]+)$</from> <to>/world.jsp</to> </rule> <!--应用wildcard表达式,该表达式后面会介绍--> <rule match-type="wildcard"> <from>/world/*/*</from> <to>/world.jsp</to> </rule>
wildcard 表达式匹配方法
用wildcard 可以取代正则表达式,要使用该表达式的时候记得要在rule 元素中 把match-type 设为 wildcard ,因为默认是使用正则表达式的。
实例:
/big/url/*
匹配 /big/url/abc.html
不匹配 /big/url/abc/dir/
or /big/url/abc/
/big/url/**
匹配/big/url/abc.html
, /big/url/abc/dir/
和 /big/url/abc/
实例:
/my/big/url/*
匹配 /my/big/url/abc.html
和$1
将被设为 abc.html