URL Rewriting in Java and Spring

Unknown picture Unknown · Nov 2, 2011 · Viewed 15.4k times · Source

I am new to Java and spring.I need to know how we can achieve URL rewriting in Java and Spring. For example in .NET environment we can achieve this by using following code:

Global.asax.cs:

protected void Application_BeginRequest(object sender, EventArgs e) {
  try {
    string fullOrigionalpath = Request.Url.ToString();
    if (fullOrigionalpath.Contains("/Home-Page")) {
      Context.RewritePath("~/home.aspx"); return;
    }
  }
}

Similarly,we need to achieve in Java and Spring.

  1. Can we have anything related to this in Java and Spring?
  2. If we cannot do using above code,How we can achieve URL Rewriting?

Help would be appreciated.

Answer

Lincoln picture Lincoln · Nov 23, 2011

I would recommend using OCPsoft Rewrite (beta) or OCPsoft PrettyFaces (final), which are newer and more evolved tools for doing Java Servlet URL-rewriting.

Rewrite also has support for your tuckey configuration, if you want to take advantage of your existing configuration, and add in more powerful Java-based Rewrite configuration.

It is very stable and well tested.

package com.example;
public class ExampleConfigurationProvider extends HttpConfigurationProvider
{
   @Override
   public int priority()
   {
     return 10;
   }

   @Override
   public Configuration getConfiguration(final ServletContext context)
   {
     return ConfigurationBuilder.begin()
       .defineRule()
         .when(Direction.isInbound().and(Path.matches("/some/{page}/.*/")))
         .perform(Redirect.permanent("/new-{page}/"));
    }
}