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

I wrote a ReST application with JAX-RS using Apache Wink, and I understood the concept of the association between path parameters and the resource descriptor class. Here I see that we can determine the paths using the @Path annotation and the corresponding resource that will be called based on the HTTP method.

Now I'm looking at something like a resource that should be called for a variable number of path parameters.

For example, I want my only CollegeResource resource CollegeResource to be called for URIs such as /rest/college, /rest/college/subject, /rest/college/subject/teachers, , and it can go to any number of path parameters.

If I know the number of path parameters in the previous one, I could achieve this using something like this /rest/college/{param1}/{param2} . But the number of path parameters is unknown. Therefore, I felt (maybe I'm mistaken) can not use this approach.

Another way I could use is to use query parameters. But I want this to be available only as path parameters.

Is there any way to do this using apache under any other configuration? If not in Apache, do any other JAX-RS implementations support this?

+5
source share
1 answer

You can use a regular expression, for example @Path("/college/{param: .*}") , And then use List<PathSegment> as a parameter to the method. for instance

 @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 semantic meaning. The resolution of an arbitrary number of path parameters, which may not have any meaning, is error prone, and IMO is the cause of redesign. I would need to know the semantics underlying this design before I can offer any advice.

+7
source

Source: https://habr.com/ru/post/1215243/


All Articles