Accept comma separated value in REST Webservice

隐身守侯 提交于 2019-12-22 08:23:34

问题


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

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

, where abc and test are the comma separated values passed in).

Currently I am getting this value as 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 any better method to achieve the same?


回答1:


I am not sure what you are trying to achieve with your service, however, it may be better to use query parameters to get multiple values for a single 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();
} 



回答2:


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

there are a number of things you can do with matrix variables but those require ; and key/value pairs which is not what you're using.

Things I found (apart from the matrix stuff) How to pass comma separated parameters in a url for the get method of rest service How can I map semicolon-separated PathParams in Jersey?



来源:https://stackoverflow.com/questions/26564464/accept-comma-separated-value-in-rest-webservice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!