第一歩:在web应用中导入需要的jar包,使用Maven就是在Maven配置pom.xml加入urlrewrite包依赖。
<dependency>
<groupId>org.tuckey</groupId>
<artifactId>urlrewritefilter</artifactId>
</dependency>
<dependency>
<groupId>ro.isdc.wro4j</groupId>
<artifactId>wro4j-core</artifactId>
</dependency>第二步,使用过滤器自然要在web.xml中加入filter的配置,filter-mapping的位置要考虑好,通常应该是在比较前面的位置,只在编码和本地化之类的过滤器格式之后。
<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>第三步:在WEB-INF目录下建一个urlrewrite.xml文件,通过正则表达式编写地址重写的规则。urlrewrite.xml简单来说就是配置rule和outbound-rule。当用户访问服务器时的URL会与rule结点比较。rule中form的规则默认使用的是正则表达式来匹配的,如果符合规则就会按照下面to结点中的配置对其进行跳转,其默认是forward跳转。当服务器需要给用户返回数据是url重写是通过outbound-rule来实现的,配置规则和rule大致相同。下面给个简单配置例子。
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.0//EN"
"http://www.tuckey.org/res/dtds/urlrewrite3.0.dtd">
<urlrewrite default-match-type="wildcard">
<!-- 定义struts无关规则 -->
<rule>
<from>/</from>
<to type="redirect" last="true">home</to>
</rule>
<rule>
<from>/j_security_check</from>
<to>/j_security_check</to>
</rule>
<rule>
<from>/images/**</from>
<to>/images/$1</to>
</rule>
<rule>
<from>/scripts/**</from>
<to>/scripts/$1</to>
</rule>
<rule>
<from>/styles/**</from>
<to>/styles/$1</to>
</rule>
<rule>
<from>/login*</from>
<to>/login.jsp</to>
</rule>
<rule>
<from>/logout*</from>
<to>/logout.jsp</to>
</rule>
<!-- Struts 去除,加上actino-->
<rule match-type="regex">
<from>^([^?]*)/([^?/\.]+)(\?.*)?$</from>
<to last="true">$1/$2.action$3</to>
</rule>
<outbound-rule match-type="regex">
<from>^(.*)\.action(\?.*)?$</from>
<to last="false">$1$2</to>
</outbound-rule>
</urlrewrite>大功告成!开发过程中有问题可以把filter的debug level打开,查看更多debug的log分析。原文地址:http://blog.csdn.net/cloud_ll/article/details/41911179