`
angelbill3
  • 浏览: 252889 次
  • 性别: Icon_minigender_2
  • 来自: 杭州
社区版块
存档分类
最新评论

利用 urlrewrite 对Struts2 url进行重写

 
阅读更多
STRUTS2中有各种ACTION,DO等结尾的URL,看起来很不美观,URL重写很有必要。
我用的是urlrewrite-3.0.4.jar 网上搜了下,应该有更高版本。


web.xml配置:
<!-- Url重写 -->
    <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>
    </filter-mapping>
    <filter>
<!-- Url重写结束 -->

<!--默认页-->
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

<!--struts2配置-->
<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>/struts/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>*.jsp</url-pattern>
	<dispatcher>REQUEST </dispatcher>    
      	<dispatcher>FORWARD </dispatcher>    
       	<dispatcher>INCLUDE </dispatcher>
    </filter-mapping>
    <filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>*.action</url-pattern>
	<dispatcher>REQUEST </dispatcher>    
      	<dispatcher>FORWARD </dispatcher>    
       	<dispatcher>INCLUDE </dispatcher>
    </filter-mapping>


然后在WEB-INF下建xml文件 取名:urlrewrite.xml
<urlrewrite>
    <!--{1}-->    
    <rule>  
        <from>^/index.html</from>  
        <to type="forward">/index.action</to>  
    </rule>  

    <!--{2}-->    
    <rule>  
        <from>^/book-([0-9]+).html$</from>  
        <to type="forward">  
        /indexbook.action?bookid=$1  
        </to>  
    </rule> 

    <!--{3}-->    
    <rule>  
        <from>^/depart-([0-9]+)-([0-9]+).html$</from>  
        <to type="forward">  
        /indexdepartbook.action?departmentId=$1&amp;majorId=$2  
        </to>  
    </rule>  

    <!--{4}-->    
    <rule>		
	<from>^/(.*)(.html)$</from>
	<to>/$1.action</to>
    </rule>
</urlrewrite>

只要在webroot下建一个空白文件叫index.html 就能直接通过index.html来访问首页的action了。
{1}意思是你访问index.html的时候,实际访问的其实是index.action。
{2}访问book-1.html 等于 indexbook.action?bookid=1
{3}多个参数,访问depart-1-0.html 等于 indexdepartbook.action?departmentId=1&majorId=0
{4}拦截所有的后缀为action的URL,URL重写为action名+html后缀。

补充:
若带参数的地址是字符 则用:(\S{1,10}) ---- S表示String,1,10表示10最长长度为10.
如:

    <rule>  
        <from>^/(\S{1,10}).html$</from>  
        <to type="forward">/indexindex.action?forshort=$1</to>  
    </rule> 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics