This post originated from an RSS feed registered with Java Buzz
by Russell Beattie.
Original Post: URL Rewrite Filter
Feed Title: Russell Beattie Notebook
Feed URL: http://www.russellbeattie.com/notebook/rss.jsp?q=java,code,mobile
Feed Description: My online notebook with thoughts, comments, links and more.
I found this great library last night while implementing something similar, and was able to toss what I had done (which was just short of sucky) and use Paul Tuckey's URL Rewrite Filter instead. It's basically a Java version of Mod rewrite and it does everything that I wanted it to, and it does it better than what I had come up with.
It's implemented as a Filter, which is great. I had implemented my rewrite code as a Servlet at first and was refactoring it into a Filter when I discovered this library. It's a bit heavy on the libraries (2 MB's of jakarta stuff), but the code is BSD and looks pretty clean. The best way to understand it's functionality is to look at the sample URLRewrite.xml file that came with it:
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>
Isn't that pretty slick? Notice the type attribute allows both redirects and forwards which is great for testing, and the user-agent stuff is *perfect* for serving up different pages for different platforms (i.e. mobile phones).
I was hacking my way along to something like this, but hadn't gotten there yet. This is much nicer and is ridiculously easy to slipstream into any app because of the way its implemented to call .jsps and servlets as per normal.