Spring - Rewrite one URL to another

George picture George · Feb 25, 2010 · Viewed 15.7k times · Source

I have a Spring 2.5 application that contains a Flash banner. I don't have the source for the Flash component but it has links hardcoded to certain pages that end in .html I want to be able to redirect those .html pages to existing jsp pages. How can I have Spring resolve a few .html pages to .jsp pages?

My project looks like:

WebContent
 |
 -sample.jsp
 -another.jsp
  WEB-INF
  |
  -myapp-servlet.xml
  -web.xml

I want localhost:8080/offers.html to redirect to localhost:8080/sample.jsp

Can I do this with Spring? I already have a SimpleUrlHandlerMapping and UrlFilenameViewController defined in the myapp-servlet.xml that has to continue serving the pages it already is.

In my web.xml, I have

<servlet-mapping>
  <servlet-name>myapp</servlet-name>
  <url-pattern>*.htm</url-pattern>
</servlet-mapping>

Update

Here is the URL mapper. If I add a controller, how do I return the jsp view that is in the WebContent directory as the view resolver includes the /WEB-INF/jsp directory.

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
  <property name="mappings">
    <props>
      <prop key="/page1.htm">page1Controller</prop>
      <prop key="/page2.htm">page2Controller</prop>
    </props>
  </property>
</bean>

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
</bean>

Answer

Hans Westerbeek picture Hans Westerbeek · Feb 25, 2010

I think you could benefit from the open source URL Rewriting library made by tuckey.org. The guys at SpringSource endorse this library, since it is set up for you automatically if you use Spring Roo to create a project, so it is of good quality. I have used it successfully in a number of projects.

See here for its homepage. And Skaffman is right, you want it to 'forward' instead of redirect, which is the default behaviour.

Configure it in web.xml like this:

<filter>
        <filter-name>UrlRewriteFilter</filter-name>
        <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>

Then, in WEB-INF/urlrewrite.xml have an element like this:

<rule>
    <from>offers.html</from>
    <to>offers.jsp</to>     
</rule>