silent_coder
silent_coder

Reputation: 6502

Jersey (JAX-RS) how to map path with multiple optional parameters

I need to map path with multiple optional arguments to my endpoint

path will look like localhost/func1/1/2/3 or localhost/func1/1 or localhost/func1/1/2 and this path should be correctly matched with

public Double func1(int p1, int p2, int p3){ ... }

What should I use in my annotations?

It's test task to play with Jersey to find a way for using multiple optional params, not to learn REST design.

Upvotes: 5

Views: 6567

Answers (2)

Ph0en1x
Ph0en1x

Reputation: 10067

To solve this you need to make your params optional, but also / sign optional

In the final result it will looks similar to this:

    @Path("func1/{first: ((\+|-)?\d+)?}{n:/?}{second:((\+|-)?\d+)?}{p:/?}{third:((\+|-)?\d+)?}")
    public String func1(@PathParam("first") int first, @PathParam("second") int second, @PathParam("third") int third) {
        ...
    }

Upvotes: 9

wumpz
wumpz

Reputation: 9131

You should give QueryParams a try:

@GET
@Path("/func1")
public Double func1(@QueryParam("p1") Integer p1, 
                    @QueryParam("p2") Integer p2, 
                    @QueryParam("p3") Integer p3) {
...
}

which would be requested like:

localhost/func1?p1=1&p2=2&p3=3

Here all parameters are optional. Within the path part this is not possible. The server could not distinguish between e.g.:

func1/p1/p3 and func1/p2/p3

Here are some examples of QueryParam usage: http://www.mkyong.com/webservices/jax-rs/jax-rs-queryparam-example/.

Upvotes: 7

Related Questions