`
nwenji
  • 浏览: 13885 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

URL重写

 
阅读更多

 

 原文:http://blog.csdn.net/ygf215/article/details/4766285

 

 1、简介  

    UrlRewriteFilter是一个用于改写URL的Web过滤器,类似于Apache的mod_rewrite。适用于任何Web应用服务器(如Resin,Orion,Tomcat等)。其典型应用就把动态URL静态化,便于搜索引擎爬虫抓取你的动态网页。

 其主页:http://tuckey.org/urlrewrite/

 

 

2、安装

    在其主页下载该包文件,把其jar 包放在lib 目录下,在web.xml 中添加下面内容

Xml代码 
  1. <filter>  
  2.     <filter-name>UrlRewriteFilter</filter-name>  
  3.     <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>  
  4. </filter>  
  5. <filter-mapping>  
  6.     <filter-name>UrlRewriteFilter</filter-name>  
  7.     <url-pattern>/*</url-pattern>  
  8.     <dispatcher>REQUEST</dispatcher>  
  9.     <dispatcher>FORWARD</dispatcher>  
  10. </filter-mapping>  

 在 WEB-INF目录下放置urlrewrite.xml 其配置文件。重启应用即可完成安装。

 

3、参数介绍

   (1)web.xml 下的filter 参数设置介绍

Xml代码 
  1.  <filter>  
  2.         <filter-name>UrlRewriteFilter</filter-name>  
  3.         <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>  
  4.   
  5.         <!-- set the amount of seconds the conf file will be checked for reload  
  6.         can be a valid integer (0 denotes check every time,  
  7.         -1 denotes no reload check, default -1)  
  8. 设置定时检查配置文件的时间以供重新加载的时间,该参数值为整型,0为每次都检查,-1为从不检查,默认为-1  
  9.  -->  
  10.         <init-param>  
  11.             <param-name>confReloadCheckInterval</param-name>  
  12.             <param-value>60</param-value>  
  13.         </init-param>  
  14.   
  15.         <!-- if you need to the conf file path can be changed  
  16.         it is specified as a path relative to the root of your context  
  17.         (default /WEB-INF/urlrewrite.xml)   
  18. 设置配置文件的路径  
  19. -->  
  20.         <init-param>  
  21.             <param-name>confPath</param-name>  
  22.             <param-value>/WEB-INF/urlrewrite.xml</param-value>  
  23.         </init-param>  
  24.   
  25.         <!-- sets up log level (will be logged to context log)  
  26.         can be: TRACE, DEBUG, INFO (default), WARN, ERROR, FATAL, log4j, commons, slf4j,  
  27.         sysout:{level} (ie, sysout:DEBUG)  
  28.         if you are having trouble using normal levels use sysout:DEBUG  
  29.         (default WARN)  
  30. 设置日志的等级  
  31.  -->  
  32.         <init-param>  
  33.             <param-name>logLevel</param-name>  
  34.             <param-value>DEBUG</param-value>  
  35.         </init-param>  
  36.   
  37.         <!-- you can change status path so that it does not  
  38.         conflict with your installed apps (note, defaults  
  39.         to /rewrite-status) note, must start with /   
  40. 设置状态目录,必须以/开始,默认为/rewrite-status  
  41. -->  
  42.         <init-param>  
  43.             <param-name>statusPath</param-name>  
  44.             <param-value>/status</param-value>  
  45.         </init-param>  
  46.   
  47.         <!-- you can disable status page if desired  
  48.         can be: true, false (default true)   
  49. 是否允许状态页面,默认为true  
  50. -->  
  51.         <init-param>  
  52.             <param-name>statusEnabled</param-name>  
  53.             <param-value>true</param-value>  
  54.         </init-param>  
  55.   
  56.         <!-- you may want to allow more hosts to look at the status page  
  57.         statusEnabledOnHosts is a comma delimited list of hosts, * can  
  58.         be used as a wildcard (defaults to "localhost, local, 127.0.0.1")   
  59. 设置host 的列表,可以使用通配符,多个host 用逗号隔开  
  60. -->  
  61.         <init-param>  
  62.             <param-name>statusEnabledOnHosts</param-name>  
  63.             <param-value>localhost, dev.*.myco.com, *.uat.mycom.com</param-value>  
  64.         </init-param>  
  65.   
  66.   
  67.         <!-- defaults to false. use mod_rewrite style configuration file (if this is true and confPath  
  68.         is not specified confPath will be set to /WEB-INF/.htaccess) -->  
  69.         <init-param>  
  70.             <param-name>modRewriteConf</param-name>  
  71.             <param-value>false</param-value>  
  72.         </init-param>  
  73.   
  74.         <!-- load mod_rewrite style configuration from this parameter's value.  
  75.                 note, Setting this parameter will mean that all other conf parameters are ignored.  
  76.             <init-param>  
  77.                 <param-name>modRewriteConfText</param-name>  
  78.                 <param-value>  
  79.                     RewriteRule ^/~([^/]+)/?(.*) /u/$1/$2 [R]  
  80.                     RewriteRule ^/([uge])/([^/]+)$ /$1/$2/ [R]  
  81.                 </param-value>  
  82.             </init-param>  
  83.         -->  
  84.   
  85.         <!-- defaults to false. allow conf file to be set by calling /rewrite-status/?conf=/WEB-INF/urlrewrite2.xml  
  86.                 designed to be used for testing only  
  87.             <init-param>  
  88.                 <param-name>allowConfSwapViaHttp</param-name>  
  89.                 <param-value>false</param-value>  
  90.             </init-param>  
  91.         -->  
  92.   
  93.     </filter>  
  94.   
  95.     <filter-mapping>  
  96.         <filter-name>UrlRewriteFilter</filter-name>  
  97.         <url-pattern>/*</url-pattern>  
  98.         <dispatcher>REQUEST</dispatcher>  
  99.         <dispatcher>FORWARD</dispatcher>  
  100.     </filter-mapping>  

 

 

(2)urlrewrite.xml 配置文件参数

 

 

Xml代码 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.   
  3. <!DOCTYPE urlrewrite  
  4.     PUBLIC "-//tuckey.org//DTD UrlRewrite 3.0//EN"  
  5.     "http://tuckey.org/res/dtds/urlrewrite3.0.dtd">  
  6.   
  7. <urlrewrite>  
  8.   
  9.     <rule>  
  10.        <from>^/some/olddir/(.*)$</from>  
  11.        <to type="redirect">/very/newdir/$1</to>  
  12.     </rule>  
  13.   
  14.     <rule match-type="wildcard">  
  15.        <from>/blog/archive/**</from>  
  16.        <to type="redirect">/roller/history/$1</to>  
  17.     </rule>  
  18.   
  19. </urlrewrite>  

 

 

 配置文件规则:

urlrewirte 配置文件必须有一个urlrewrite根元素和包含至少一个rule元素 。

一个rule元素必须包含一个from 和一个to 元素,也可以包含0个以上的condition 元素和0个以上set 元素。

一个rule元素拦截用户的请求,from元素 是请求的url,to 元素是经过重写后的url 输出,下面是类似java 的重写内部实现。 

Java代码 
  1. Pattern.compile(<from> element);  
  2.     pattern.matcher(request url);  
  3.     matcher.replaceAll(<to> element);  
  4.     if ( <condition> elements match && matcher.find() ) {  
  5.         handle <set> elements (if any)  
  6.         execute <run> elements (if any)  
  7.         perform <to> element (if any)  
  8.     }  

 

 (4)元素参数说明

<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 应用那种匹配规则

 

实例代码:

 

Xml代码 
  1.   <!--请求输入: /world/usa/nyc   输出为  /world.jsp   -->  
  2. <!--应用java 的正则表达式-->  
  3. <rule match-type="regex">  
  4.        <from>^/world/([a-z]+)/([a-z]+)$</from>  
  5.        <to>/world.jsp</to>  
  6.     </rule>  
  7. <!--应用wildcard表达式,该表达式后面会介绍-->  
  8.  <rule match-type="wildcard">  
  9.        <from>/world/*/*</from>  
  10.        <to>/world.jsp</to>  
  11.     </rule  

 

 

<outbound-rule>元素

 

参数 取值 描述
enabled true(默认)、false 是否应该该规则
encodefirst false(默认)、false 是否在执行<outbound-rule>之前执行encodeURL(),ture为之后,false为之前

 

实例:

Xml代码 
  1. <outbound-rule>  
  2.     <from>^/world.jsp?country=([a-z]+)&amp;city=([a-z]+)$</from>  
  3.     <to>/world/$1/$2</to>  
  4. </outbound-rule>  

 

 

Java代码 
  1. 使用jsp  
  2. <a href="<%= response.encodeURL("/world.jsp?country=usa&amp;city=nyc") %>">nyc</a>   
  3. 将输出  
  4. <a href="/world/usa/nyc">nyc</a>   
  5.   
  6. 或者使用jstl 标签  
  7. <a href="<c:url value="/world.jsp?country=${country}&amp;city=${city}" />">nyc</a>   
  8. 将输出  
  9. <a href="/world/usa/nyc">nyc</a>   

 

<name>元素

Xml代码 
  1. <!--该规则的名称,可以用在rule元素和outbound-rule 元素中-->  
  2.   
  3. lt;rule>  
  4.        <name>World Rule</name>  
  5.        <from>^/world/([a-z]+)/([a-z]+)$</from>  
  6.        <to>/world.jsp?country=$1&amp;city=$2</to>  
  7.   </rule>  

 <note>元素

Xml代码 
  1. <!--用来描述该规则,可用在rule 元素和outbound-rule元素中-->  
  2. lt;rule>  
  3.        <name>World Rule</name>  
  4.        <note>  
  5.            Cleanly redirect world requests to JSP,  
  6.            a country and city must be specified.  
  7.        </note>  
  8.        <from>^/world/([a-z]+)/([a-z]+)$</from>  
  9.        <to>/world.jsp</to>  
  10.    </rule>  

 <condition>元素

可以用来为rule元素选择条件,所有条件将在规则执行时执行(除非显式的把“next” 设为“or”)

 

参数 取值 描述
type header(默认)、method、port、time等 设置一些条件的类型
name 可为任何值 如果type 取值为header,这个名称将是http header 的值
next and(默认)、or and:下一个rule 元素和这个rule 必须匹配。or:下一个rule元素或者这个condition 将被匹配
operator equal(默认)、notequal、greater、less等 ie请求的值和condition 值比较

 

实例:

Xml代码 
  1. <condition name="user-agent" operator="notequal">Mozilla/[1-4]</condition>  
  2.   
  3.     <condition type="user-in-role" operator="notequal">bigboss</condition>  
  4.   
  5.     <condition name="host" operator="notequal">www.example.com</condition>  
  6.   
  7.     <condition type="method" next="or">PROPFIND</condition>  
  8.     <condition type="method">PUT</condition>  

 

<from> 元素

rule 或者outbound-rule 必须至有一个from 元素,该值为url 相对于上下文的值

 

参数 取值 描述
casesensitive false(默认)、true 是否要求该值的大小写,false为大小写匹配,true为忽略大小写

 

 

<to>元素

重写后的输出值

 

参数 取值 描述
type forward(默认)、passthrough、redirect等 url 的跳转问题
last false(默认)、true

false:余下的rule 元素将被执行,如果该规则符合的话

true:剩下的rule 元素不被执行,如果该规则符合的话

encode false(默认)、true

response.encodeURL([to]) 是否被调用。

false:将在url重写前调用。

true:将不被调用

context  

如果应用服务器配置允许 cross context(跨越上下文),这个属性将被forward(只有forward可以,redirct 或者其他to元素的类型都不可以)

比如在tomcat 的配置文件中设有:

<Context docBase="app" path="/app" reloadable="true" crossContext="true"/> 
<Context docBase="forum" path="/forum" reloadable="true" crossContext="true"/>

 

<to>null</to>表示当这个规则匹配时,将不会有任何的反应。

to元素可以包含后引用(backreferences)和变量

Backreferences

比如: %N
    Provides access to the grouped parts (parentheses) of the pattern from the last matched Condition in the current rule. N must be less than 10 and greater than 0 (i.e. %1, %2, %3 etc). 

(上面不理解,未翻译)

 

变量

%{varName}

任何变量的 condition type 可以被用来作为varName。比如:%{port}将被翻译为80 ,%{year}将被翻译成2009等

 

函数

%{function:params}

函数可以用在set元素或者to元素中。

 

名称 实例 输入结果
replace ${replace:my cat is a blue cat:cat:dog} my dog is a blue dog
replaceFirst ${replace:my cat is a blue cat:cat:dog} my cat is a blue dog
escape ${escape:a b c} a+b+c
unescape ${unescape:a+b+c} a b c
lower ${lower:Hello World} hello world
upper ${upper:hello} HELLO
trim ${trim: abc def } abc def

 

set元素

如果rule 匹配的话,允许你设置一些变量。

 

参数 取值 描述
type request、session、cookie、charset等 设置域的类型
name 任何数

在request、session、response-header、cookie,有特殊的作用

 

实例:

Xml代码 
  1.     
  2. <!--把client 的值设进request中,可通过request.getAttribute("client")来获取-->  
  3.  <rule>  
  4.         <condition name="user-agent">Mozilla/3/.0 (compatible; AvantGo .*)</from>  
  5.         <from>.*</from>  
  6.         <set name="client">AvantGo</set>  
  7.     </rule>  
  8.     <rule>  
  9.         <condition name="user-agent">UP/.Browser/3.*SC03 .* </from>  
  10.         <from>.*</from>  
  11.         <set name="client">Samsung SCH-6100</set>  
  12.     </rule>  

 

<run> 元素

当rule和它的condition匹配时,你可以运行Object中的一个方法

 

参数 取值 描述
class   你所要调用的方法的Object
method run(默认) 你所要调用的方法,该方法必须带有(HttpServletRequest, HttpServletResponse)参数。例如:run(HttpServletRequest request, HttpServletResponse response) 
如果init(ServletConfig) 或者destroy() 方法,将会被执行,当创建或销毁该Object时
neweachtime false(默认)、true 该Oject 是否为单例执行。false为单例,true为每次都new 新的Object

 

实例:

Java代码 
  1. <rule>  
  2.        <from>^/world/[a-z]+/[a-z]+$</from>  
  3.        <run class="com.blah.web.WorldServlet" method="doGet" />  
  4.        <to>/world-presentation.jsp</to>  
  5.    </rule>  
  6. lt;!--可以设置一些初始值-->  
  7.   <run class="com.blah.web.MyServlet" method="doGet">  
  8.        <init-param>  
  9.            <param-name>someParamName</param-name>  
  10.            <param-value>10</param-value>  
  11.        </init-param>  
  12.    </run>  

 

才此方法中出现的异常将会被包装成ServletException 后抛出。

 

<class-rule>元素

每次请求都执行这个方法在rule 元素中,具体的例子在org.tuckey.web.filters.urlrewrite.sample可以查看。

 

参数 取值 描述
class   运行的Object,必须带有包的全名

method

matches(默认) 运行的方法,和run元素中的方法类似
last true(默认) 当为false时更多的rule将被执行,即使寂静匹配

 

实例:

Xml代码 
  1. <class-rule class="com.blah.web.MyRuleClass" />  

 

4、小知识点

  (1)xml 的一些字符必须要进行转义,如& 要转成 $amp;

  (2)正则表达式里 在from 元素中,是以 ^ 开始 $结束的。例如请求:/my/url/path 将不能匹配 <from>^/url/$</from> 但能匹配<from>/url/</from>

  (3)如果你用了<outbound-rule> 元素,记得在页面输出的时候进行重写。即 jstl 表达式或者Java脚本输出

  (4)如果你发现正则表达式比较难表达,可以用wildcards 表达式来写。

 

5、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/

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics