javarestjax-rsapache-wink

How to write single JAX-RS resource for variable number of path parameters


I have been writing a JAX-RS based ReST application using Apache Wink and I understood the concept of association between path params to resource handle class. Here I see that, We can define paths using @Path annotation and corresponding resource which will get called based on HTTP Method..

Now I am looking at something like a resource which should get called for variable number of path parameters.

For example I want my single resource class CollegeResource should be called for URIs like /rest/college, /rest/college/subject, /rest/college/subject/teachers, and it can go up to any number of path parameters.

If I know the number of path params in prior then I could have achieved this using something like this /rest/college/{param1}/{param2}. But number of path params is unknown. So I felt (I may be wrong) can not use this approach.

One more way I could still use is using query parameters. But I want this to be available to be as path params only.

Is there any way to get this done using apache wink with any other configuration ? If not in Apache wink, any other JAX-RS implementaions support this ?


Solution

  • You can use a regex, like @Path("/college/{param: .*}"), then use List<PathSegment> as a method parameter. For example

    @GET
    @Path("/college/{params: .*}")
    public Response get(@PathParam("params") List<PathSegment> params) {
        StringBuilder builder = new StringBuilder();
        for (PathSegment seg: params) {
            builder.append(seg.getPath());
        }
        return Response.ok(builder.toString()).build();
    }
    

    C:\>curl -v http://localhost:8080/college/blah/hello/world/cool
    Result: blahhelloworldcool

    But personally, I would stay away from this kind of thing. Your URI paths (templates) should have some semantic meaning. Allowing an arbitrary number of path params, that may not have any meaning, is error prone, and IMO, is a cause for redesign. I would need to know the semantics behind this design choice before I can offer any advice though.