您的位置:首页 > 编程语言 > Java开发

java中的UrlReWriter(url重写)_源码下载

2012-11-12 12:53 363 查看
最近在做的一个项目中用到了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

<?xml version="1.0" encoding="UTF-8"?>
<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"
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">

<!-- url重写start -->
<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>
<!-- url重写end -->

<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


/UrlReWriter/WebContent/WEB-INF/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">
<!-- Configuration file for UrlRewriteFilter http://tuckey.org/urlrewrite/ -->
<urlrewrite>
<rule>
<from>/test.html</from>
<to type="redirect">%{context-path}/duona.html</to>
</rule>
<rule>
<from>/name/(.*)</from>
<to>/MyName.jsp?name=$1</to>
</rule>
</urlrewrite>


/UrlReWriter/WebContent/duona.html

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


/UrlReWriter/WebContent/test.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
this is a test html page!
</body>
</html>


/UrlReWriter/WebContent/MyName.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath %>"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><%=request.getParameter("name")%></title>
</head>
<body>
my name is :<font color="red"> <%=request.getParameter("name")%> </font>,welcome to my zone:<br />
<a href="http://www.cnblogs.com/hongten">http://www.cnblogs.com/hongten</a><br />
<img alt="多拿网" src="img/iduona.jpg">
</body>
</html>


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

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

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

package org.tuckey.web.filters.urlrewrite.sample;

import org.tuckey.web.filters.urlrewrite.Conf;
import org.w3c.dom.Document;

import java.io.InputStream;

public class SampleConfExt extends Conf {

public SampleConfExt() {
// do something
}

protected synchronized void loadDom(InputStream inputStream) {
// do something
super.loadDom(inputStream);
}

protected void processConfDoc(Document doc) {
// do something else
super.processConfDoc(doc);
}
}


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

package org.tuckey.web.filters.urlrewrite.sample;

import org.tuckey.web.filters.urlrewrite.Conf;
import org.tuckey.web.filters.urlrewrite.UrlRewriteFilter;
import org.tuckey.web.filters.urlrewrite.UrlRewriter;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.FileInputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
* Sample of how you might load multiple configuration files. (NOT to be used verbatim!!)
*/
public class SampleMultiUrlRewriteFilter extends UrlRewriteFilter {

private List urlrewriters = new ArrayList();

public void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {
// add configurations
try {
Conf conf1 = new Conf(filterConfig.getServletContext(), new FileInputStream("someconf.xml"), "someconf.xml", "");
urlrewriters.add(new UrlRewriter(conf1));

Conf conf2 = new SampleConfExt();
urlrewriters.add(new UrlRewriter(conf2));

} catch (Exception e) {
throw new ServletException(e);
}
}

public UrlRewriter getUrlRewriter(ServletRequest request, ServletResponse response, FilterChain chain) {
// do some logic to decide what urlrewriter to use (possibly do a reload check on the conf file)
return (UrlRewriter) urlrewriters.get(0);
}

public void destroyUrlRewriter() {
for (int i = 0; i < urlrewriters.size(); i++) {
UrlRewriter urlRewriter = (UrlRewriter) urlrewriters.get(i);
urlRewriter.destroy();
}
}

}


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

/**
* Copyright (c) 2005-2007, Paul Tuckey
* All rights reserved.
* ====================================================================
* Licensed under the BSD License. Text as follows.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   - Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   - Neither the name tuckey.org nor the names of its contributors
*     may be used to endorse or promote products derived from this
*     software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
package org.tuckey.web.filters.urlrewrite.sample;

import org.tuckey.web.filters.urlrewrite.extend.RewriteMatch;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* A sample of how you might write a custom match.
*/
class SampleRewriteMatch extends RewriteMatch {
private int id;

SampleRewriteMatch(int i) {
id = i;
}

int getId() {
return id;
}

public boolean execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// lookup things in the db based on id

// do something like forward to a jsp
request.setAttribute("sampleRewriteMatch", this);
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/jsp/some-view.jsp");
rd.forward(request, response);
// in the jsp you can use request.getAttribute("sampleRewriteMatch") to fetch this object

return true;
}

}


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

/**
* Copyright (c) 2005-2007, Paul Tuckey
* All rights reserved.
* ====================================================================
* Licensed under the BSD License. Text as follows.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   - Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   - Neither the name tuckey.org nor the names of its contributors
*     may be used to endorse or promote products derived from this
*     software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
package org.tuckey.web.filters.urlrewrite.sample;

import org.tuckey.web.filters.urlrewrite.extend.RewriteRule;
import org.tuckey.web.filters.urlrewrite.extend.RewriteMatch;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* A sample of how you might write a custom rule.
*/
public class SampleRewriteRule extends RewriteRule {

public RewriteMatch matches(HttpServletRequest request, HttpServletResponse response) {

// return null if we don't want the request
if (!request.getRequestURI().startsWith("/staff/")) return null;

Integer id = null;
try {
// grab the things out of the url we need
id = Integer.valueOf(request.getRequestURI().replaceFirst(
"/staff/([0-9]+)/", "$1"));
} catch (NumberFormatException e) {
// if we don't get a good id then return null
return null;
}

// match required with clean parameters
return new SampleRewriteMatch(id.intValue());
}

}


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

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

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.2//EN"
"http://tuckey.org/res/dtds/urlrewrite3.2.dtd">

<!--

Configuration file for UrlRewriteFilter http://tuckey.org/urlrewrite/ 
-->
<urlrewrite>

<rule>
<note>
The rule means that requests to /test/status/ will be redirected to /rewrite-status
the url will be rewritten.
</note>
<from>/test/status/</from>
<to type="redirect">%{context-path}/rewrite-status</to>
</rule>

<outbound-rule>
<note>
The outbound-rule specifies that when response.encodeURL is called (if you are using JSTL c:url)
the url /rewrite-status will be rewritten to /test/status/.

The above rule and this outbound-rule means that end users should never see the
url /rewrite-status only /test/status/ both in thier location bar and in hyperlinks
in your pages.
</note>
<from>/rewrite-status</from>
<to>/test/status/</to>
</outbound-rule>

<!--

INSTALLATION

in your web.xml add...

<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>
</filter-mapping>

EXAMPLES

Redirect one url
<rule>
<from>/some/old/page.html</from>
<to type="redirect">/very/new/page.html</to>
</rule>

Redirect a directory
<rule>
<from>/some/olddir/(.*)</from>
<to type="redirect">/very/newdir/$1</to>
</rule>

Clean a url
<rule>
<from>/products/([0-9]+)</from>
<to>/products/index.jsp?product_id=$1</to>
</rule>
eg, /products/1234 will be passed on to /products/index.jsp?product_id=1234 without the user noticing.

Browser detection
<rule>
<condition name="user-agent">Mozilla/[1-4]</condition>
<from>/some/page.html</from>
<to>/some/page-for-old-browsers.html</to>
</rule>
eg, will pass the request for /some/page.html on to /some/page-for-old-browsers.html only for older
browsers whose user agent srtings match Mozilla/1, Mozilla/2, Mozilla/3 or Mozilla/4.

Centralised browser detection
<rule>
<condition name="user-agent">Mozilla/[1-4]</condition>
<set type="request" name="browser">moz</set>
</rule>
eg, all requests will be checked against the condition and if matched
request.setAttribute("browser", "moz") will be called.

-->

</urlrewrite>


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

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

项目源码下载:http://files.cnblogs.com/hongten/UrlReWriter.rar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐