Why use a Url Rewrite Filter in Spring?

peasoup picture peasoup · Aug 24, 2010 · Viewed 7.9k times · Source

A Spring app I'm using declares a Tuckey UrlReWrite Filter and then sets up a rewrite rule as the following:

<rule>
    <from>^/(.*)$</from>
    <to last="true">/app/$1</to>
</rule>

Why do this?

Will Spring not be able to recognize requests that do not go to the /app/ url?

Otherwise what is the advantage of this redirect?

Answer

axtavt picture axtavt · Aug 24, 2010

Imagine that you want Spring MVC's DispatcherServlet to handle all URLs in your application excluding the URLs of static content. If you try to do it directly with <url-pattern>/</url-pattern>, this mapping will take precedence over the static content.

With rewrite filter you can specify exclusions for the static content, like this:

<urlrewrite default-match-type="wildcard">
    <rule>
        <from>/staticContentHere/**</from>
        <to>/staticContentHere/$1</to>
    </rule>
    <rule>
        <from>/**</from>
        <to>/app/$1</to>
    </rule>    
</urlrewrite>

EDIT: Note that since Spring 3.0.4 there is a <mvc:resources /> declaration. With this declaration, DispatcherServlet will serve static content from the /resources subfolder of your webapp, so rewriting will not be needed (see http://blog.springsource.com/2010/07/22/spring-mvc-3-showcase/).