urlrewriter 的用法

来源:互联网 发布:淘宝美版三星s7能买吗 编辑:程序博客网 时间:2024/06/06 00:13

本博客的部分内容来自于其它博客,对原作者表示感谢。

参考文献:http://urlrewritefilter.googlecode.com/svn/trunk/src/doc/manual/3.2/index.html

如何增强你网站中地址的可读性和让搜索引擎快速的收录到你的站点,这就需要你美化你的网页的地址,

也就是我们常说的Url重写技术,大家熟悉的可能有很多服务器都提供Url重写的技术,以前我们用的最多的就是Apache,

Jboss这样一些服务器自带的一些Url重写,但是他们的配置比较麻烦,性能又不是太好,现在我们有专一的开源框架

来完成Url重写任务,今天我要介绍的就是UrlRewriter。使用起来比较简单,配置是相当的简单明了。

我们先简单的了解一下使用Url重写能给你网站带来哪些好处。

  第一:有利于搜索引擎的抓取,因为现在大部分的搜索引擎对动态页面的抓取还比较弱,它们更喜欢抓取一些静态的页面。

    而我们现在的页面大部分的数据都是动态的显示的。这就需要我们把动态页面变成静态的页面,有利于搜索引擎的抓取。

  第二:让用户更容易理解,很少有用户去关心你网站的页面的地址,但对一般的大中型网站增强可读性还是必须的。这样会让你的网站更加完美。

  第三:隐藏技术的实现,我们可以通过Url重写可以实现技术的隐藏。不至于暴露你所采用的技术,给一些想攻击你网站的爱好者提供方便。

  第四:可以很方便的重用,提高网站的移植性。如果我们后台方法改动的话,可以保证前台的页面部分不用改。这样就提高了网站的移植性。

它虽然有这么多的优点,但是也有一点缺点的,因为它是通过过滤器原理来实现的,就以为着又多了一道访问,会多少影响点访问速度的,这个可以忽略不计的。

现在UrlRewriter技术有两个技术平台的,一个就是在Java方向的,另一个就是.NET方向的。今天我们讲的是Java方向的应用。

首先让我们了解它的工作原理,说白了它就是一个简单的过滤器(Filter) ,看看源码你就会很快的明白,它就是通过我们在jsp中常用的两个方法实现的forward(),sendRedirect().

下面我们就快速的为你的网站搭建Url重写技术。

==============================================

如何增强你网站中地址的可读性和让搜索引擎快速的收录到你的站点,这就需要你美化你的网页的地址,也就是我们常说的Url重写技术,大家熟悉的可能有很多服务器都提供Url重写的技术,以前我们用的最多的就是Apache,Jboss这样一些服务器自带的一些Url重写,但是他们的配置比较麻烦,性能又不是太好,现在我们有专一的开源框架来完成Url重写任务,今天我要介绍的就是UrlRewriter。使用起来比较简单,配置是相当的简单明了。

     我们先简单的了解一下使用Url重写能给你网站带来哪些好处。
    第一:有利于搜索引擎的抓取,因为现在大部分的搜索引擎对动态页面的抓取还比较弱,它们更喜欢抓取一些静态的页面。而我们现在的页面大部分的数据都是动态的显示的。这就需要我们把动态页面变成静态的页面,有利于搜索引擎的抓取。
    第二:让用户更容易理解,很少有用户去关心你网站的页面的地址,但对一般的大中型网站增强可读性还是必须的。这样会让你的网站更加完美。
    第三:隐藏技术的实现,我们可以通过Url重写可以实现技术的隐藏。不至于暴露你所采用的技术,给一些想攻击你网站的爱好者提供方便。
    第四:可以很方便的重用,提高网站的移植性。如果我们后台方法改动的话,可以保证前台的页面部分不用改。这样就提高了网站的移植性。

   它虽然有这么多的优点,但是也有一点缺点的,因为它是通过过滤器原理来实现的,就以为着又多了一道访问,会多少影响点访问速度的,这个可以忽略不计的。
   现在UrlRewriter技术有两个技术平台的,一个就是在Java方向的,另一个就是.NET方向的。今天我们讲的是Java方向的应用。
   首先让我们了解它的工作原理,说白了它就是一个简单的过滤器(Filter) ,看看源码你就会很快的明白,它就是通过我们在jsp中常用的两个方法实现的forward(),sendRedirect().
   下面我们就快速的为你的网站搭建Url重写技术。
   第一步:下载urlrewrite-2.6.0.现在最新版本是3.1的。
   http://tuckey.org/urlrewrite/dist/urlrewritefilter-2.6.zip
   http://urlrewritefilter.googlecode.com/files/urlrewritefilter-3.1.0.zip
   把urlrewrite-2.6.0.jar拷到classpath下。

   第二步:在web.xml中初始化。加上下面的代码:

  1.   <!-- Set URL Rewrite-->  
  2. <filter>  
  3.  <filter-name>UrlRewriteFilter</filter-name>  
  4.  <filter-class>  
  5.   org.tuckey.web.filters.urlrewrite.UrlRewriteFilter   
  6.  </filter-class>  
  7. </filter>  
  8. <filter-mapping>  
  9.  <filter-name>UrlRewriteFilter</filter-name>  
  10.  <url-pattern>/*</url-pattern>  
  11. </filter-mapping>  

   第三步:在WEB-INF目录下建一个urlrewrite.xml文件。

   所有的规则配置都写在这里。第一个常用个规则就是站内的简单重写。

[html] view plaincopy
  1. <rule>  
  2.   <note>一些说明</note>  
  3.   <from>写上你自己定义的访问地址</from>    
  4.   <to>就是实际的访问地址</to>    
  5. </rule>  
  6. <rule>  
  7.    <note>  
  8.    假设实际的访问地址是:http://yousite.com/entity.htm?category=user&page=2,即to  
  9.    而我们想把它重写为http://yousite.com/entity/uesr/page_2.html,即from  
  10.    我们就应该这样的写:  
  11.    </note>  
  12.   <from>^/(\w+)/(\w+)/page_(\d+)\.html$</from>    
  13.   <to type="forward">/$1.htm?category=$2&page=$3</to> 非常重要:这里应将 & 换成 &amp;
  14.  </rule>    
[html] view plaincopy
  1. <rule>  
  2.    <note>  
  3.    假设实际的访问地址是:http://localhost:8080/user/search.action?gender=Male&name=Mary,即to  
  4.    而我们想把它重写为http://localhost:8080/user/search/Male/Mary.html,即from  
  5.    我们就应该这样的写:  
  6.    </note>  
  7.   <from>^/(\w+)/(\w+)/(\w+).html$</from>    
  8.   <to>/$1.action?gender=$2&name=$3</to>  
  9.  </rule>    

 简单的介绍一下常用的正规表示式:  
代码 说明 
. 匹配除换行符以外的任意字符 
\w 匹配字母或数字或下划线或汉字 
\s 匹配任意的空白符 
\d 匹配数字 
\b 匹配单词的开始或结束 
^ 匹配字符串的开始 
$ 匹配字符串的结束

常用的&要用  &amp;来表示。$1,$2代表与你配置正规表达式/(\w+)/(\w+)/相对应的参数。<to type="forward">默认的是 type="forward".
  另一个常用的规则就是连接外部的网站。就要用到。<to type="redirect">

  1. <rule>  
  2.     <from>^/rss/yahoo\.html$</from>  
  3.       <to type="redirect">http://add.my.yahoo.com/rss? url=http://feed.feedsky.com/MySiteFeed[/url]   
  4.      </to>  
  5. </rule>  

==============================================

下面我们就来实现一个的url重写例子:

准备工作:

下载:urlrewrite-3.2.0.jar

可以到这里下载:http://code.google.com/p/urlrewritefilter/downloads/list

我下载的是:urlrewrite-3.2.0.jar

1.项目结构

2.运行效果1

输入:http://localhost:8080/UrlReWriter/name/hongten

3.运行效果2:

输入:http://localhost:8080/UrlReWriter/test.html

不错吧,是不是想自己动手试一试啊.

==============================================

/UrlReWriter/WebContent/WEB-INF/web.xml

复制代码
 1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 3     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> 4  5     <!-- url重写start --> 6     <filter>    7          <filter-name>UrlRewriteFilter</filter-name>    8          <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>    9      </filter>   10      <filter-mapping>   11          <filter-name>UrlRewriteFilter</filter-name>   12          <url-pattern>/*</url-pattern>   13          <dispatcher>REQUEST</dispatcher>   14          <dispatcher>FORWARD</dispatcher>   15      </filter-mapping>16     <!-- url重写end -->17 18 19     <welcome-file-list>20         <welcome-file>index.html</welcome-file>21         <welcome-file>index.htm</welcome-file>22         <welcome-file>index.jsp</welcome-file>23     </welcome-file-list>24 </web-app>
复制代码

/UrlReWriter/WebContent/WEB-INF/urlrewrite.xml

复制代码
 1 <?xml version="1.0" encoding="utf-8"?> 2  <!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.0//EN" 3          "http://tuckey.org/res/dtds/urlrewrite3.0.dtd"> 4 <!-- Configuration file for UrlRewriteFilter http://tuckey.org/urlrewrite/ --> 5 <urlrewrite> 6     <rule> 7         <from>/test.html</from> 8         <to type="redirect">%{context-path}/duona.html</to> 9     </rule>10     <rule>11         <from>/name/(.*)</from>12         <to>/MyName.jsp?name=$1</to>13     </rule>14 </urlrewrite>
复制代码

/UrlReWriter/WebContent/duona.html

复制代码
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 5 <title>多拿网</title> 6 </head> 7 <body> 8  红色字体加粗测试 :<br /> 9 <font color="red" >多拿网,'码'上行动,多拿多优惠</font><br />10 测试连接地址:<br />11 <a href="http://www.iduona.com" target="_blank">多拿网</a><br />12 图片测试:<br />13 <img alt="多拿网" src="img/iduona.jpg">14 </body>15 </html>
复制代码

/UrlReWriter/WebContent/test.html

复制代码
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 5 <title>Insert title here</title> 6 </head> 7 <body> 8 this is a test html page! 9 </body>10 </html>
复制代码

/UrlReWriter/WebContent/MyName.jsp

复制代码
 1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2     pageEncoding="UTF-8"%> 3 <% 4 String path = request.getContextPath(); 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 6 %> 7 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 8 <html> 9 <head>10 <base href="<%=basePath %>"/>11 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">12 <title><%=request.getParameter("name")%></title>13 </head>14 <body>15 my name is :<font color="red"> <%=request.getParameter("name")%> </font>,welcome to my zone:<br />16 <a href="http://www.cnblogs.com/hongten">http://www.cnblogs.com/hongten</a><br />17 <img alt="多拿网" src="img/iduona.jpg">18 </body>19 </html>
复制代码

==============================================

下面和大家分享一下:org.tuckey.web.filters.urlrewrite.sample包下面的一些源代码

org.tuckey.web.filters.urlrewrite.sample.SampleConfExt.class

复制代码
 1 package org.tuckey.web.filters.urlrewrite.sample; 2  3 import org.tuckey.web.filters.urlrewrite.Conf; 4 import org.w3c.dom.Document; 5  6 import java.io.InputStream; 7  8  9 public class SampleConfExt extends Conf {10 11     public SampleConfExt() {12         // do something13     }14 15     protected synchronized void loadDom(InputStream inputStream) {16         // do something17         super.loadDom(inputStream);18     }19 20     protected void processConfDoc(Document doc) {21         // do something else22         super.processConfDoc(doc);23     }24 }
复制代码

org.tuckey.web.filters.urlrewrite.sample.SampleMultiUrlRewriteFilter.class

复制代码
 1 package org.tuckey.web.filters.urlrewrite.sample; 2  3 import org.tuckey.web.filters.urlrewrite.Conf; 4 import org.tuckey.web.filters.urlrewrite.UrlRewriteFilter; 5 import org.tuckey.web.filters.urlrewrite.UrlRewriter; 6  7 import javax.servlet.FilterChain; 8 import javax.servlet.FilterConfig; 9 import javax.servlet.ServletException;10 import javax.servlet.ServletRequest;11 import javax.servlet.ServletResponse;12 import java.io.FileInputStream;13 import java.net.URL;14 import java.util.ArrayList;15 import java.util.List;16 17 /**18  * Sample of how you might load multiple configuration files. (NOT to be used verbatim!!)19  */20 public class SampleMultiUrlRewriteFilter extends UrlRewriteFilter {21 22     private List urlrewriters = new ArrayList();23      24     public void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {25         // add configurations26         try {27             Conf conf1 = new Conf(filterConfig.getServletContext(), new FileInputStream("someconf.xml"), "someconf.xml", "");28             urlrewriters.add(new UrlRewriter(conf1));29 30             Conf conf2 = new SampleConfExt();31             urlrewriters.add(new UrlRewriter(conf2));32 33         } catch (Exception e) {34             throw new ServletException(e);35         }36     }37 38     public UrlRewriter getUrlRewriter(ServletRequest request, ServletResponse response, FilterChain chain) {39         // do some logic to decide what urlrewriter to use (possibly do a reload check on the conf file)40         return (UrlRewriter) urlrewriters.get(0);41     }42 43     public void destroyUrlRewriter() {44         for (int i = 0; i < urlrewriters.size(); i++) {45             UrlRewriter urlRewriter = (UrlRewriter) urlrewriters.get(i);46             urlRewriter.destroy();47         }48     }49 50 }
复制代码

org.tuckey.web.filters.urlrewrite.sample.SampleRewriteMatch.class

复制代码
 1 /** 2  * Copyright (c) 2005-2007, Paul Tuckey 3  * All rights reserved. 4  * ==================================================================== 5  * Licensed under the BSD License. Text as follows. 6  * 7  * Redistribution and use in source and binary forms, with or without 8  * modification, are permitted provided that the following conditions 9  * are met:10  *11  *   - Redistributions of source code must retain the above copyright12  *     notice, this list of conditions and the following disclaimer.13  *   - Redistributions in binary form must reproduce the above14  *     copyright notice, this list of conditions and the following15  *     disclaimer in the documentation and/or other materials provided16  *     with the distribution.17  *   - Neither the name tuckey.org nor the names of its contributors18  *     may be used to endorse or promote products derived from this19  *     software without specific prior written permission.20  *21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE25  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER29  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE32  * POSSIBILITY OF SUCH DAMAGE.33  * ====================================================================34  */35 package org.tuckey.web.filters.urlrewrite.sample;36 37 import org.tuckey.web.filters.urlrewrite.extend.RewriteMatch;38 39 import javax.servlet.RequestDispatcher;40 import javax.servlet.ServletException;41 import javax.servlet.http.HttpServletRequest;42 import javax.servlet.http.HttpServletResponse;43 import java.io.IOException;44 45 46 /**47  * A sample of how you might write a custom match.48  */49 class SampleRewriteMatch extends RewriteMatch {50     private int id;51 52     SampleRewriteMatch(int i) {53         id = i;54     }55 56     int getId() {57         return id;58     }59 60     public boolean execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {61 62         // lookup things in the db based on id63 64         // do something like forward to a jsp65         request.setAttribute("sampleRewriteMatch", this);66         RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/jsp/some-view.jsp");67         rd.forward(request, response);68         // in the jsp you can use request.getAttribute("sampleRewriteMatch") to fetch this object69 70         return true;71     }72 73 }
复制代码

org.tuckey.web.filters.urlrewrite.sample.SampleRewriteRule.class

复制代码
 1 /** 2  * Copyright (c) 2005-2007, Paul Tuckey 3  * All rights reserved. 4  * ==================================================================== 5  * Licensed under the BSD License. Text as follows. 6  * 7  * Redistribution and use in source and binary forms, with or without 8  * modification, are permitted provided that the following conditions 9  * are met:10  *11  *   - Redistributions of source code must retain the above copyright12  *     notice, this list of conditions and the following disclaimer.13  *   - Redistributions in binary form must reproduce the above14  *     copyright notice, this list of conditions and the following15  *     disclaimer in the documentation and/or other materials provided16  *     with the distribution.17  *   - Neither the name tuckey.org nor the names of its contributors18  *     may be used to endorse or promote products derived from this19  *     software without specific prior written permission.20  *21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE25  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER29  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE32  * POSSIBILITY OF SUCH DAMAGE.33  * ====================================================================34  */35 package org.tuckey.web.filters.urlrewrite.sample;36 37 import org.tuckey.web.filters.urlrewrite.extend.RewriteRule;38 import org.tuckey.web.filters.urlrewrite.extend.RewriteMatch;39 40 import javax.servlet.http.HttpServletRequest;41 import javax.servlet.http.HttpServletResponse;42 43 /**44  * A sample of how you might write a custom rule.45  */46 public class SampleRewriteRule extends RewriteRule {47 48 49     public RewriteMatch matches(HttpServletRequest request, HttpServletResponse response) {50 51         // return null if we don't want the request52         if (!request.getRequestURI().startsWith("/staff/")) return null;53 54         Integer id = null;55         try {56             // grab the things out of the url we need57             id = Integer.valueOf(request.getRequestURI().replaceFirst(58                 "/staff/([0-9]+)/", "$1"));59         } catch (NumberFormatException e) {60             // if we don't get a good id then return null61             return null;62         }63 64         // match required with clean parameters65         return new SampleRewriteMatch(id.intValue());66     }67 68 }
复制代码

还有:org.tuckey.web.filters.urlrewrite包下面的conf-dist.xml文件

/org/tuckey/web/filters/urlrewrite/conf-dist.xml

复制代码
 1 <?xml version="1.0" encoding="utf-8"?> 2 <!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.2//EN" 3         "http://tuckey.org/res/dtds/urlrewrite3.2.dtd"> 4  5 <!-- 6  7     Configuration file for UrlRewriteFilter 8     http://tuckey.org/urlrewrite/ 9 10 -->11 <urlrewrite>12 13     <rule>14         <note>15             The rule means that requests to /test/status/ will be redirected to /rewrite-status16             the url will be rewritten.17         </note>18         <from>/test/status/</from>19         <to type="redirect">%{context-path}/rewrite-status</to>20     </rule>21 22 23     <outbound-rule>24         <note>25             The outbound-rule specifies that when response.encodeURL is called (if you are using JSTL c:url)26             the url /rewrite-status will be rewritten to /test/status/.27 28             The above rule and this outbound-rule means that end users should never see the29             url /rewrite-status only /test/status/ both in thier location bar and in hyperlinks30             in your pages.31         </note>32         <from>/rewrite-status</from>33         <to>/test/status/</to>34     </outbound-rule>35 36 37     <!--38 39     INSTALLATION40 41         in your web.xml add...42 43         <filter>44             <filter-name>UrlRewriteFilter</filter-name>45             <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>46             <init-param>47                 <param-name>logLevel</param-name>48                 <param-value>WARN</param-value>49             </init-param>50         </filter>51         <filter-mapping>52             <filter-name>UrlRewriteFilter</filter-name>53             <url-pattern>/*</url-pattern>54         </filter-mapping>55 56      EXAMPLES57 58      Redirect one url59         <rule>60             <from>/some/old/page.html</from>61             <to type="redirect">/very/new/page.html</to>62         </rule>63 64     Redirect a directory65         <rule>66             <from>/some/olddir/(.*)</from>67             <to type="redirect">/very/newdir/$1</to>68         </rule>69 70     Clean a url71         <rule>72             <from>/products/([0-9]+)</from>73             <to>/products/index.jsp?product_id=$1</to>74         </rule>75     eg, /products/1234 will be passed on to /products/index.jsp?product_id=1234 without the user noticing.76 77     Browser detection78         <rule>79             <condition name="user-agent">Mozilla/[1-4]</condition>80             <from>/some/page.html</from>81             <to>/some/page-for-old-browsers.html</to>82         </rule>83     eg, will pass the request for /some/page.html on to /some/page-for-old-browsers.html only for older84     browsers whose user agent srtings match Mozilla/1, Mozilla/2, Mozilla/3 or Mozilla/4.85 86     Centralised browser detection87         <rule>88             <condition name="user-agent">Mozilla/[1-4]</condition>89             <set type="request" name="browser">moz</set>90         </rule>91     eg, all requests will be checked against the condition and if matched92     request.setAttribute("browser", "moz") will be called.93 94     -->95 96 </urlrewrite>
复制代码

总结:有没理解它的工作原理,说白了它就是一个简单的过滤器(Filter) ,看看源码你就会很快的明白,

它就是通过我们在jsp中常用的两个方法实现的forward(),sendRedirect().

项目源码下载:http://files.cnblogs.com/hongten/UrlReWriter.rar

====================================================================================

下面的内容非常重要

urlrewriter 和 Struts2 整合

准备工作先要有2个配置文件+1个jar包

配置文件1:urlrewrite.xml

写道
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.0//EN" 
"http://tuckey.org/res/dtds/urlrewrite3.0.dtd"> 

<urlrewrite> 
<rule> 
<note> 
<!-- 这是一个通用请求url rewrite 
将请求forword url加上".action"的处理器上。例: 
请求 http://{domain}/user/login 将被forward到 http://{domain}/user/login.do 
请求 http://{domain}/user/login/ 将被forward到 http://{domain}/user/login.do 
请求 http://{domain}/user/logout/ 将被forward到 http://{domain}/user/logout.do 
--> 
</note> 
<from>^/([_a-zA-Z]+[_0-9a-zA-Z-/]*[_0-9a-zA-Z]+)/?.html$</from> 
<to type="forward">/$1.action</to> 
</rule> 
<!-- 
<rule> 
<note>这是一个通用请求url rewrite</note> 
<from>^/([a-z0-9A-Z_]+)/([a-z0-9A-Z_]+)/!([a-z0-9A-Z_]+).html$</from> 
<to type="forward">/$2.action?id=$1</to> 
</rule> 
--> 
<!-- Override default validation.js from WebWork --> 
<rule> 
<from>^/struts/css_xhtml/validation.js$</from> 
<to type="forward">/template/css_xhtml/validation.js</to> 
</rule> 

<!-- The following fixes a bug in XFire: --> 
<!-- http://jira.codehaus.org/browse/XFIRE-1089 --> 
<rule> 
<from>^//services/(.*)$</from> 
<to type="forward">/services/$1</to> 
</rule> 
</urlrewrite> 

 

配置文件2:web.xml

在web.xml文件中插入一个filter

写道
<!-- UrlRewriteFilter filter --> 
<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>

 

1个jar包:urlrewritefilter-3.1.0.jar

 

但是这样配置会遇到问题

因此需要在web.xml文件中添加一个东西,完整的filter链如下:

写道
<!-- UrlRewriteFilter filter --> 
<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> 
<!-- Struts2 filter --> 
<filter> 
<filter-name>struts2-cleanup</filter-name> 
<filter-class> 
org.apache.struts2.dispatcher.ActionContextCleanUp 
</filter-class> 
</filter> 
<filter-mapping> 
<filter-name>UrlRewriteFilter</filter-name> 
<url-pattern>/*</url-pattern> 
<dispatcher>REQUEST</dispatcher> 
<dispatcher>FORWARD</dispatcher> 
</filter-mapping> 
<filter-mapping> 
<filter-name>struts2-cleanup</filter-name> 
<url-pattern>/*</url-pattern> 
<dispatcher>REQUEST</dispatcher> 
<dispatcher>FORWARD</dispatcher> 
</filter-mapping> 

<filter> 
<filter-name>struts2</filter-name> 
<filter-class> 
org.apache.struts2.dispatcher.FilterDispatcher 
</filter-class> 
</filter> 
<filter-mapping> 
<filter-name>struts2</filter-name> 
<url-pattern>/*</url-pattern> 
<dispatcher>REQUEST</dispatcher> 
<dispatcher>FORWARD</dispatcher> 
</filter-mapping> 

<filter> 
<filter-name>encodingFilter</filter-name> 
<filter-class> 
org.springframework.web.filter.CharacterEncodingFilter 
</filter-class> 
<init-param> 
<param-name>encoding</param-name> 
<param-value>UTF-8</param-value> 
</init-param> 
</filter> 
<filter-mapping> 
<filter-name>encodingFilter</filter-name> 
<url-pattern>/*</url-pattern> 
</filter-mapping>

 1、在web.xml中EncodingFilter的位置应该在Struts2的FilterDispatcher之前,道理很简单,要先调整字符集,再进入Action。 

2、如果使用Urlrewrite,要指定filter-mapping的dispatcher方式,如下 
<filter-mapping> 
    <filter-name>Struts2</filter-name> 
    <url-pattern>/*</url-pattern> 
    <dispatcher>REQUEST</dispatcher> 
    <dispatcher>FORWARD</dispatcher> 
</filter-mapping> 

3、在做上传文件的时候,要在web.xml中增加ActionContextCleanUp这个filter,如果不增加,会发生第一次上传取不到文件的情况 
<filter> 
  <filter-name>struts-cleanup</filter-name> 
  <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class> 
  </filter> 
  <filter-mapping> 
    <filter-name>struts-cleanup</filter-name> 
    <url-pattern>/*</url-pattern> 
  </filter-mapping> 
按照Struts2的API,filter的顺序是 
struts-cleanup filter 
SiteMesh filter 
FilterDispatcher


只看完这篇博文还不够,此时你应该再看下面这篇博文

http://blog.csdn.net/jackieliulixi/article/details/38335615


如果你不看,会遇到下面这个问题:


在 urlrewriter.xml 中有如下配置

Plain Text code
?
1
2
3
4
5
6
7
8
9
10
11
<urlrewrite>
    <rule>
        <from>^/(\w+).html$</from>
        <to type="forward">$1.action</to>
    </rule>
     
    <rule>
        <from>^/(\w+)/(\w+)/(\w+)$</from>
        <to type="forward">/$1.action?userName=$2&amp;password=$3</to>
    </rule>
</urlrewrite>


在这里 如果在浏览器地址栏中输入http://localhost:8080/brook/userLogin.html
地址会映射到 http://localhost:8080/brook/userLogin.action,这是一个登录页面。
但现在不懂的问题是,我在登录页面中输入登录信息后,通过下面的表单提交
XML/HTML code
?
1
<form id="loginform" method="post" class="form-vertical"action="doLogin.action">

此时浏览器显示地址为 http://localhost:8080/brook/doLogin.action
但我想把地址显示成 http://localhost:8080/brook/index.html

请问各位我该如何进行配置呢。

0 0
原创粉丝点击