Search code examples
javarestjax-rsjersey-2.0path-parameter

Jersey howto iterate over parameters?


I have this put request that needs lot of parameters.

So is there a way to iterate over the parameters instead of manually accesing them.

@PUT
@Path("/{foobar}")
public Response createFoobar(
        @PathParam("foo1") String foo1,
        @PathParam("foo2") String foo2, 
        @PathParam("foo3") String foo3,
        @PathParam("foo4") String foo4
        ...
{
    FooBar foobar = new FooBar();
    foobar.foo1 = foo1;
    foobar.foo2 = foo2;
    ...

    return Response.status(200)...;
}

What i want

foreach(Object param in pathParams){
    if(param.name.equals("foo1")
        foobar.setFoo1((String)param);
    if(param.name.equals("foo2")
        foobar.setFoo2((String)param);
    ...
}

Is this possible?


Solution

  • You can obtain query- and path parameters from UriInfo:

    @GET
    public String get(@Context UriInfo ui) {
        MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
        MultivaluedMap<String, String> pathParams = ui.getPathParameters();
    }
    

    To obtain the parameters from the application/x-www-form-urlencoded content of a POST or PUT request, inject a javax.ws.rs.core.Form object into the controller method:

    @PUT
    public String put(Form form) {
        MultivaluedMap<String, String> formParams = form.asMap();
    }