Accept comma separated value in REST Webservice

I am trying to get a list of String as comma separated value in a REST URI (sample:

http://localhost:8080/com.vogella.jersey.first/rest/todo/test/1/abc,test 

      

where abc and test are comma separated values ​​passed to).

Currently I am getting this value as a string and then splitting it to get the individual values. Current code:

@Path("/todo")
public class TodoResource {
// This method is called if XMLis request
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/test/{id: .*}/{name: .*}")
public Todo getXML(@PathParam("id") String id,
        @PathParam("name") String name) {
    Todo todo = new Todo();
    todo.setSummary("This is my first todo, id received is : " + id
            + "name is : " + Arrays.asList(name.split("\\s*,\\s*")));
    todo.setDescription("This is my first todo");
    TodoTest todoTest = new TodoTest();
    todoTest.setDescription("abc");
    todoTest.setSummary("xyz");
    todo.setTodoTest(todoTest);
    return todo;
}
}

      

Is there a better way to achieve the same?

+3


source to share


2 answers


I'm not sure what you are trying to achieve with your service, however it is better to use query parameters to get multiple values ​​for one parameter. Consider the below URL.

http://localhost:8080/rest/todos?name=name1&name=name2&name=name3 

      



And here is the code snippet for the REST service.

@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/todos")
public Response get(@QueryParam("name") List<String> names) {

    // do whatever you need to do with the names

   return Response.ok().build();
} 

      

+5


source


If you don't know how many comma separated values ​​you get, then the split you are doing as far as I could find the best way to do it. If you know you will always have 3 comma separated values, you can get those 3. directly (for example, if you have lat, long, or x, y, z, then you can get it with three path variables. ( see one of the stackoverflow links posted below)

there are a number of things you can do with matrix variables, but this is required; and key / value pairs that you are not using.



Things I've found (besides matrix stuff) How to pass comma separated parameters in url for getter method of rest How can I match semicolon separated PathParams in Jersey?

0


source







All Articles