Search code examples
restlet

Restlet - redirecting to a resource


I'm trying to redirect /boxes/{id} to /boxes/{id}/description (Restlet 2.3.7):

Redirector redirector = new Redirector(getContext(),
        "/boxes/{id}/description",
        Redirector.MODE_CLIENT_SEE_OTHER);
router.attach("/boxes/{id}", redirector);

This seems to work except when deployed to a Servlet container under a non-root URL path. In that case, the base path is omitted from the Location header, and so the redirect does not work.

The book, "Restlet in Action," shows the Redirector working with an absolute URI. I'm aware that HTTP/1.1 does not allow redirecting to paths, but Restlet does create the rest of the URI for me in the Location header, except the Servlet root path part.

I have found this old mailing list posting, but it seems like there has to be a better way.


Solution

  • I solved this by creating a new Resource to handle redirection:

    public class BoxesResource extends ServerResource {
    
        public static class RedirectingResource extends ServerResource {
            @Get
            public Representation doGet() {
                final String id = (String) this.getRequest().
                        getAttributes().get("id");
                final Reference newRef = new Reference(
                        getRootRef().toString() + "/boxes/" + id + "/description");
                redirectSeeOther(newRef);
                return new EmptyRepresentation();
            }
        }
    
        @Get
        public Representation doGet() {
            // ...
        }
    
    }
    

    Then I attached it in my Application's createInboundRoot():

    router.attach("/boxes/{id}", BoxesResource.RedirectingResource.class);
    router.attach("/boxes/{id}/description", BoxesResource.class);