Thursday, July 8, 2010

How to URL Rewrite in Spring MVC

I am in the process of writing a Groovy based web app with Spring MVC and I wanted to use URL Rewriting. I scoured the boards for HOWTO's and from all my research's URLRewrite is the best one out there. Here's a quick tutorial on how to set it up.

First, you need to add the dependency to your pom:

Next you need to map the URL Rewrite filter and your Spring Dispatcher servlet in your web.xml:

Then in src/main/webapp/WEB-INF you need to define a urlrewrite.xml. This file defines the filters for your webapp. For my app, I keep all JSP files under WEB-INF/jsp and use Spring's InternalResourceViewResolver to forward to them. This is great, except since my filter takes all request, I have to supply rules for the static files like html, javascript, css, images etc.

Here's how you do that. In urlrewrite.xml add the following:

That's it, URL rewriting is enabled on your app. Now anytime someone hits a URL in your app like http://[server]:[port]/[context-root]/[controller]/[action] (depending on which HandlerMapping you use) the filter will forward the request to the dispatcher servlet and your appropriate controller. For anything that goes to /images /js /css or /html, they will be forwarded to those resources.

I hope this is helpful.