java中的UrlReWriter(url重寫)_源碼下載


最近在做的一個項目中用到了url重寫。

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

如何增強你網站中地址的可讀性和讓搜索引擎快速的收錄到你的站點,這就需要你美化你的網頁的地址,

也就是我們常說的Url重寫技術,大家熟悉的可能有很多服務器都提供Url重寫的技術,以前我們用的最多的就是Apache,

Jboss這樣一些服務器自帶的一些Url重寫,但是他們的配置比較麻煩,性能又不是太好,現在我們有專一的開源框架

來完成Url重寫任務,今天我要介紹的就是UrlRewriter。使用起來比較簡單,配置是相當的簡單明了。

我們先簡單的了解一下使用Url重寫能給你網站帶來哪些好處。

  第一:有利於搜索引擎的抓取,因為現在大部分的搜索引擎對動態頁面的抓取還比較弱,它們更喜歡抓取一些靜態的頁面。

    而我們現在的頁面大部分的數據都是動態的顯示的。這就需要我們把動態頁面變成靜態的頁面,有利於搜索引擎的抓取。

  第二:讓用戶更容易理解,很少有用戶去關心你網站的頁面的地址,但對一般的大中型網站增強可讀性還是必須的。這樣會讓你的網站更加完美。

  第三:隱藏技術的實現,我們可以通過Url重寫可以實現技術的隱藏。不至於暴露你所采用的技術,給一些想攻擊你網站的愛好者提供方便。

  第四:可以很方便的重用,提高網站的移植性。如果我們后台方法改動的話,可以保證前台的頁面部分不用改。這樣就提高了網站的移植性。

它雖然有這么多的優點,但是也有一點缺點的,因為它是通過過濾器原理來實現的,就以為着又多了一道訪問,會多少影響點訪問速度的,這個可以忽略不計的。

現在UrlRewriter技術有兩個技術平台的,一個就是在Java方向的,另一個就是.NET方向的。今天我們講的是Java方向的應用。

首先讓我們了解它的工作原理,說白了它就是一個簡單的過濾器(Filter) ,看看源碼你就會很快的明白,它就是通過我們在jsp中常用的兩個方法實現的forward(),sendRedirect().

下面我們就快速的為你的網站搭建Url重寫技術。

以上內容來自:http://blog.csdn.net/gchai/article/details/7874088

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

下面我們就來實現一個的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 something
13     }
14 
15     protected synchronized void loadDom(InputStream inputStream) {
16         // do something
17         super.loadDom(inputStream);
18     }
19 
20     protected void processConfDoc(Document doc) {
21         // do something else
22         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 configurations
26         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 copyright
12  *     notice, this list of conditions and the following disclaimer.
13  *   - Redistributions in binary form must reproduce the above
14  *     copyright notice, this list of conditions and the following
15  *     disclaimer in the documentation and/or other materials provided
16  *     with the distribution.
17  *   - Neither the name tuckey.org nor the names of its contributors
18  *     may be used to endorse or promote products derived from this
19  *     software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25  * 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) HOWEVER
29  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * 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 id
63 
64         // do something like forward to a jsp
65         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 object
69 
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 copyright
12  *     notice, this list of conditions and the following disclaimer.
13  *   - Redistributions in binary form must reproduce the above
14  *     copyright notice, this list of conditions and the following
15  *     disclaimer in the documentation and/or other materials provided
16  *     with the distribution.
17  *   - Neither the name tuckey.org nor the names of its contributors
18  *     may be used to endorse or promote products derived from this
19  *     software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25  * 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) HOWEVER
29  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * 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 request
52         if (!request.getRequestURI().startsWith("/staff/")) return null;
53 
54         Integer id = null;
55         try {
56             // grab the things out of the url we need
57             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 null
61             return null;
62         }
63 
64         // match required with clean parameters
65         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-status
16             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 the
29             url /rewrite-status only /test/status/ both in thier location bar and in hyperlinks
30             in your pages.
31         </note>
32         <from>/rewrite-status</from>
33         <to>/test/status/</to>
34     </outbound-rule>
35 
36 
37     <!--
38 
39     INSTALLATION
40 
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      EXAMPLES
57 
58      Redirect one url
59         <rule>
60             <from>/some/old/page.html</from>
61             <to type="redirect">/very/new/page.html</to>
62         </rule>
63 
64     Redirect a directory
65         <rule>
66             <from>/some/olddir/(.*)</from>
67             <to type="redirect">/very/newdir/$1</to>
68         </rule>
69 
70     Clean a url
71         <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 detection
78         <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 older
84     browsers whose user agent srtings match Mozilla/1, Mozilla/2, Mozilla/3 or Mozilla/4.
85 
86     Centralised browser detection
87         <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 matched
92     request.setAttribute("browser", "moz") will be called.
93 
94     -->
95 
96 </urlrewrite>

總結:有沒理解它的工作原理,說白了它就是一個簡單的過濾器(Filter) ,看看源碼你就會很快的明白,

它就是通過我們在jsp中常用的兩個方法實現的forward(),sendRedirect().

項目源碼下載:http://files.cnblogs.com/hongten/UrlReWriter.rar


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM