jersey @PathParam: how to pass a variable which contains more than one slashes
Asked Answered
R

1

5
package com.java4s;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

@Path("/customers")
public class RestServicePathParamJava4s {
    @GET
    @Path("{name}/{country}")
    @Produces("text/html")
    public Response getResultByPassingValue(
                @PathParam("name") String name,
                @PathParam("country") String country) {

        String output = "Customer name - "+name+", Country - "+country+"";
        return Response.status(200).entity(output).build();

    }
}

In web.xml I have specified URL pattern as /rest/* and in RestServicePathParamJava4s.java we specified class level @Path as /customers and method level @Path as {name}/{country}

So the final URL should be

http://localhost:2013/RestPathParamAnnotationExample/rest/customers/Java4/USA

and the response should be displayed as

Customer name - Java4, Country - USA

If I give the 2 input given below it is showing an error. How to solve this?

http://localhost:2013/RestPathParamAnnotationExample/rest/customers/Java4:kum77./@.com/USA` 

Here Java4:kum77./@.com this one is one string and it contains forward slash. how to accept this by using @PathParam or whatever I need to use MultivaluedMap. If somebody knows this plz help me. if anyone knows what is MultivaluedMap, give me a simple example?

Rigger answered 6/4, 2015 at 13:34 Comment(1)
As already answered by @peeskillet, regular expressions can be used. This is also mentioned in the JAX-RS specification itself (Section 3.4 URI Templates)Lashkar
C
7

You'll need to use a regex for for the name path expression

@Path("{name: .*}/{country}")

This will allow anything to be in the name template, and the last segment will be the country.

Test

@Path("path")
public class PathParamResource {

    @GET
    @Path("{name: .*}/{country}")
    @Produces("text/html")
    public Response getResultByPassingValue(@PathParam("name") String name,
                                            @PathParam("country") String country) {

        String output = "Customer name - " + name + ", Country - " + country + "";
        return Response.status(200).entity(output).build();
    }
}

$ curl http://localhost:8080/api/path/Java4:kum77./@.com/USA
Customer name - Java4:kum77./@.com, Country - USA

$ curl http://localhost:8080/api/path/Java4/USA
Customer name - Java4, Country - USA

Catalonia answered 6/4, 2015 at 16:21 Comment(2)
@paul-samsotha how does .* differ than .+ , as mentioned in this answerGain
@Shamil in most languages, this is the answer. It's related to regex.Catalonia

© 2022 - 2024 — McMap. All rights reserved.