开发者

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

开发者 https://www.devze.com 2023-01-14 19:49 出处:网络
is it possible to configure GET method to read variable number of URI param开发者_Python百科eters and interpret them either as variable argument (array) or collection? I know query parameters can be r

is it possible to configure GET method to read variable number of URI param开发者_Python百科eters and interpret them either as variable argument (array) or collection? I know query parameters can be read as list/set but I can't go for them in my case.

E.g.:

@GET
@Produces("text/xml")
@Path("list/{taskId}")
public String getTaskCheckLists(@PathParam("taskId") int... taskId) {
    return Arrays.toString(taskId);
}

Thanks in advance


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消