最近在做的一个项目中用到了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().