Is it possible to configure JAX-RS method with variable number of URI parameters?

前端 未结 2 689
我寻月下人不归
我寻月下人不归 2020-12-20 13:51

is it possible to configure GET method to read variable number of URI parameters and interpret them either as variable argument (array) or collection? I know query parameter

相关标签:
2条回答
  • 2020-12-20 13:53

    If I understand your question correctly, the @Path annotation can take a regular expression to specify a list of path components. For example, something like:

    @GET
    @Path("/list/{taskid:.+}")
    public String getTaskCheckLists(@PathParam("taskid") List<PathSegment> taskIdList) {
        ......
    }
    

    There's a more extensive example here.

    0 讨论(0)
  • 2020-12-20 14:06

    I am not submitting this as an answer as it is merely an edge case on the currently accepted answer which is what I've also used. In my case (Jersey 1.19) /list/{taskid:.+} would not work for the edge case of zero variable parameters. Changing the RegEx to /list/{taskid:.*} took care of that. See also this article (which seems to be applicable).

    Moreover, upon changing the regexp to cardinality indicator to * (instead of +) I also had to deal programmatically with the case of empty strings as I would translate the List<PathSegment> into a List<String> (to pass it into my DB-access code).

    The reason I am translating from PathSegment to String is that I didn't want a class from the javax.ws.rs.core package to pollute my Data Access Layer code.

    Here's a complete example:

    @Path("/listDirs/{dirs:.*}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response listDirs(@PathParam("dirs") List<PathSegment> pathSegments) {
        List<String> dirs = new ArrayList<>();
        for (PathSegment pathSegment: pathSegments) {
            String path = pathSegment.getPath();
            if ((path!=null) && (!path.trim().equals("")))
                dirs.add(pathSegment.getPath());
        }
        List<String> valueFromDB = db.doSomeQuery(dirs);
        // construct JSON response object ...
    }
    
    0 讨论(0)
提交回复
热议问题