This tutorial will discuss about a cool open-source project named Rewrite which is an URL-rewriting solution for Servlet, JSF, and Java EE. Rewrite offers powerful configuration, flexible extensions, and framework integration.
In order to experience a basic usage of Rewrite you need to add the rewrite-servlet dependency to your Maven projects. Since we will test rewrite on a JBoss Web application, start by creating a new project using the jboss-javaee6-webapp Archetype.
Now add the following Maven dependency to your project:
Note: If you just want to download the zip distribution from Rewrite, then you can check the following link from the Maven central Repository: Download
Now let's add a Configuration provider class which contains some rules for Rewriting an incoming URL. In our example,
let's suppose you want to rewrite an old legacy URL /view/members.xml into the REST URL /rest/members which (in the jboss-javaee6-webapp) will return an XML list of the registered members:
Here's the RESTConfigurationProvider which extends the HttpConfigurationProvider:
As you can see, the trick is done in the getConfiguration method which returns a Configuration with our Rule in it.
In order to activate our ConfigurationProvider we need to add a configuration file (in our case we will name it org.ocpsoft.rewrite.config.ConfigurationProvider ) in the folder src/main/resources/META-INF/services of your Maven project. This file will contain the Configuration Provider classes which will be activated at application deployment- in our case:
That's all. You can test your Rewrite engine using the http://localhost:8080/rewrite-demo/view/members.xml which will return the list of registered members of your application.
The Rewrite home page contains several more examples about this framework and some cool extensions available to add extra power to your Rewrite Configurations.
One useful example I'd like to mention is resource relocation which can be used to offload your servers from certain resources which can be then acquired from another server. This is usually done through the configuration of Apache Web server which should care about serving static resources. When using the Rewrite module you can however apply fine grained rules to your resource relocation as in the following example which relocates the screen.css (which is part of the jboss-javaee6-webapp Maven Archetype) to another server which is running on the host 192.168.1.1