Monday, March 14, 2011

URL rewriting for multi country website like /countryname/cityname


Hello Everyone,


Recently, i had to develop a website which needed a different URL mapping, it needed a url mapping like /France/Paris (ie: country/city).I looked out for many options, first of all i tried it with url rewriting servlet and implemented a filter with it, but it was not exactly the thing i wanted. So i looked out for other options and finally i found UrlRewriteFilter from tuckey.


I downloaded the jars from www.tuckey.org/urlrewrite and configured that in web.xml file.


I found its configuration too easy, you need to configure that in web.xml under filter tag.
<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>


Secondly, there is a seperate xml file called urlrewrite.xml that is needed by this filter.

You need to configure url rewriting rules in there. You can also use expression language to define a rule for your URL type.


So, i did someting like this to achieve my goal.

 <rule>
     <from>^/([a-z\s-] )$</from>
         <to type="redirect">%{context-path}/redirectAction.do?country=$1</to>
    </rule>
   
    <rule>
     <from>^/([a-z\s-] )/$</from>
         <to type="redirect">%{context-path}/redirectAction.do?country=$1</to>
    </rule>
   
    <rule>
     <from>^/([a-z/\s/-] )/([a-z/\s/-] )$</from>
         <to type="redirect">%{context-path}/redirectAction.do?country=$1&amp;city=$2</to>
    </rule>
      
    <rule>
     <from>^/([a-z/\s/-] )/([a-z/\s/-] )/$</from>
         <to type="redirect">%{context-path}/redirectAction.do?country=$1&amp;city=$2</to>
    </rule>


The above configuration helped me to accept multi spaced url's like www.ujjwalbsoni.blogspot.com/United States Of America/New York



I created an action in struts that gets me the names of countries and cities accordingly and i finally got what i wanted.


Expression for redirect rule was really tedious since i was having multiple spaces in country/city names. But finally, i created and succeeded in making one and using that.




Cheers!!!


Ujjwal Soni


UBS


No comments: