How to Rewrite URLs with OCPsoft Rewrite

1) Add OCPsoft Rewrite to your app as described here. It requires support for Servlet API 3.0 because it uses the methods described in section 4.4 of the spec.

2) Create the SampleConfigurationProvider class:

package br.eti.fernandoribeiro.sample;

import javax.servlet.ServletContext;

import org.ocpsoft.rewrite.config.Configuration;
import org.ocpsoft.rewrite.config.ConfigurationBuilder;
import org.ocpsoft.rewrite.servlet.config.HttpConfigurationProvider;
import org.ocpsoft.rewrite.servlet.config.rule.Join;

public final class SampleConfigurationProvider extends HttpConfigurationProvider {

  public Configuration getConfiguration(final ServletContext context) {
    // Rewrite URLs like "http://localhost/rewritesample/sample/Hello%20World!" to "http://localhost/rewritesample/sample?msg=Hello%20World!"
    return ConfigurationBuilder.begin().addRule(Join.path("/sample/{msg}").to("/sample"));

  public int priority() {
    return 0;


3) Create the WEB-INF/classes/META-INF/org.ocpsoft.rewrite.config.ConfigurationProvider file:


4) Deploy your app.

2 thoughts on “How to Rewrite URLs with OCPsoft Rewrite

  1. Hey there! Nice example🙂 I should mention that in version 1.0.6+ of Rewrite, you cannot use regular expression characters like ‘^’ in the pattern itself; you would need to use a parameter like ‘.where(“msg”).matches(“.*”)’, but this is also unnecessary in your case, because Join always matches the entire URL from start to finish.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s