JAX-RS Handle variable number FormParam

In Java, I am implementing a server where a client can transmit some data (key-value pairs) using a post request. I decided to make a REST service and I am planning on using JAX-RS along with Jetty.

I have no prior knowledge of the keys to be submitted here. Is there a way to see all the KV pairs POSTed by the client? I know that if the key is known, we can fetch the data as in -

@Path("/testpath")
public class test {

    @POST
    @Path("/level1")
    public Response getData(
        @FormParam("key1") String val1,
        @FormParam("key2") int val2) {

        return Response.status(200)
            .entity("getData is called, Key1 : " + val1 + ", Key2 : " + val2)
            .build();

    }

}

      

In the example above, I could have N different keys!

I am planning on using vanilla JAX-RS without Jersey, or RESTeasy. However, I am open to options when this is not possible in JAX-RS!

+3


source to share


1 answer


Use MultiValuedMap :



@Path("/testpath")
public class test {
    @POST
    @Path("/level1")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces("text/plain")
    public Response getData(MultiValuedMap<String, String> params) {
        StringBuilder sb = new StringBuilder("getData is called, ");
        for(String param : params.keySet()) {
            sb.append(param + " : " + params.getFirst(param) + ", ");
        }
        return Response.status(200).entity(sb.toString()).build();
    }
}

      

+2


source







All Articles