4

我正在尝试在 REST URI 中接收作为逗号分隔值的字符串列表(示例:

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

,其中 abc 和 test 是传入的逗号分隔值)。

目前我将此值作为字符串获取,然后将其拆分以获取各个值。当前代码:

@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;
}
}

有没有更好的方法来达到同样的效果?

4

2 回答 2

6

我不确定您要通过服务实现什么目标,但是,使用查询参数获取单个参数的多个值可能会更好。考虑以下 URL。

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

这是 REST 服务的代码片段。

@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();
} 
于 2014-10-26T09:49:12.780 回答
0

如果您不知道将获得多少个逗号分隔值,那么您所做的拆分就是我能找到的最佳方法。如果你知道你总是有 3 个值以逗号分隔,那么你可以直接得到这 3 个。(例如,如果您有 lat、long 或 x、y、z,那么您可以使用 3 个路径变量来获得它。(请参阅下面发布的 stackoverflow 链接之一)

你可以用矩阵变量做很多事情,但那些需要;和键/值对,这不是您正在使用的。

我发现的东西(除了矩阵的东西) 如何在 url 中为休息服务的 get 方法传递逗号分隔的参数 如何在 Jersey 中映射分号分隔的 PathParams?

于 2014-10-25T17:58:20.737 回答