简体   繁体   中英

How can I use an optional number of parameters in a Jersey REST method?

I'm new to Jersey. So, please pardon any mistake.

I'm trying to setup a simple REST ws. There is a method name getConnectedMHubs that have one required parameter thingID and two optional parameters: time and delta .

Is it possible to use the same method name for the two type of calls, with and without the optional parameters? I tried to specify two pathes but got a ModelValidationException , that says:

A resource model has ambiguous (sub-)resource method for HTTP method GET and input mime-types as defined by"@Consumes" and "@Produces" annotations at Java methods public ...

Code sample:

@Path("/api")
public class RendezvousWebService {
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("connectedmhubs/{mhubid}")
    public String getConnectedThings(@PathParam("mhubid") String strMHubID) {
        // ...
        return "{}";
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("connectedmhubs/{mhubid}/{time}/{delta}")
    public String getConnectedThingsExtended(@PathParam("mhubid") String strMHubID, @PathParam("time") long timestamp, @PathParam("delta") long delta){
        // ...
        return "{}";
    }

}

Using the @Path makes the params mandatory. You can get around this with regular expressions or you can use @QueryParam with @DefaultValue to roll the two methods into one.

Using a path pattern like this:

@Path("connectedmhubs/{mhubid}")

makes the path parameter mandatory. However, you can make use of regular expressions to overcome this limitation. See this link for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM