users@jersey.java.net

Redirect /foo/ to /foo (remove trailing slash)

From: Charles Brooking <public+java_at_charlie.brooking.id.au>
Date: Mon, 7 Sep 2009 11:11:46 +1000

Hi all,

The Redirect feature in Jersey (com.sun.jersey.config.feature.Redirect)
can be used to redirect an "unslashed" URI (eg /foo) to it's slashed
version (eg /foo/) if the @Path on a resource class ends with "/".

But in my application, I wanted the opposite: to have @Path values ending
without slashes and provide a redirect in case the user includes a slash.
Using paths without slashes seems appropriate when using MediaType
mappings (eg having /foo.html instead of /foo.html/ or /foo/.html).

I wrote a short filter to achieve this (see below). But I wonder if it's
worthwhile including this in the semantics of the existing Redirect
feature?

{{{
package au.edu.uq.itee.eresearch.dimer.webapp.app;

import java.net.URI;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;

public class RemoveSlashFilter implements ContainerRequestFilter {
  private static final String pattern = "\\/.+";

  public ContainerRequest filter(ContainerRequest request) {
    final String uri = request.getRequestUri().getRawPath().toString();
    if (uri.matches(pattern) && uri.endsWith("/")) {
      URI unslashed = URI.create(uri.substring(0, uri.length() - 1));
      Response response = Response.temporaryRedirect(unslashed).build();
      throw new WebApplicationException(response);
    }
    return request;
  }
}
}}}

Later
Charlie