Search code examples
javaservlet-filtersrestlet

Applying same filter for multiple mappings in restlet


I have a restlet in which i am applying mapping for various resources all of which are supposed to pass through a common filter, but in case the filter condition is matched, i.e for return value "CONTINUE", all the filters redirect to different resources.

public synchronized Restlet createInboundRoot()
{
   System.out.println("Called Application ");
   Router router = new Router();
   Filter fil1 = filterObj();
   router.attach("/helloworld",fil);
   fil.setNext(HelloWorldResource.class);
   router.attach("/hello",fil);
   fil.setNext(HelloWorldResource1.class);
   return router;
}

but what happens here is that at the end of execution, filter redirects to the last resource mentioned/used for setNext() , in this case HelloWorldResource1, i.e even if

http://localhost:8600/API/TRIAL/helloworld 

is called, it redirects it to HelloworldResource1.class .

this problem is resolved if I create a different filter object for each mapping and use it for redirection, but i am not sure if it is the best way to do it. Can someone guide me to the most efficient and correct way to achieve the result ?


Solution

  • Routing is chain-like in Restlet. You need to build a chain with the filter, then the router. Like this: filter->router->(resource1|resource2)

    Using your example it would blook something like:

    public synchronized Restlet createInboundRoot()
    {
     Router router = new Router();
     router.attach("/helloworld",HelloWorldResource.class);
     router.attach("/hello",HelloWorldResource1.class);
     Filter fil1 = filterObj();
     fil1.setNext(router);
     return fil1;
    }
    

    Note that a Filter is-a Restlet (it extends Restlet). See http://restlet.org/learn/javadocs/2.1/jse/api/org/restlet/routing/Filter.html