java 将来自 REST 调用的 @PathParam 值存储在列表或数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26992222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Store @PathParam values from REST call in a list or array
提问by gmode
My function looks like this:
我的功能是这样的:
@PUT
@Path("property/{uuid}/{key}/{value}")
@Produces("application/xml")
public Map<String,ValueEntity> updateProperty(@Context HttpServletRequest request,
@PathParam("key") String key,
@PathParam("value") String value,
@PathParam("uuid") String uuid) throws Exception {
...
}
I have to modify it, so it accepts indefinite(or many) list of key-value pairs from REST call, something like
我必须修改它,因此它接受来自 REST 调用的不确定(或多个)键值对列表,例如
@Path("property/{uuid}/{key1}/{value1}/{key2}/{value2}/{key3}/{value3}/...")
Is it possible to store them in an array or list, so I do not list dozens of @PathParams and parameters, to avoid this:
是否可以将它们存储在数组或列表中,所以我没有列出几十个@PathParams 和参数,以避免这种情况:
@PathParam("key1") String key1,
@PathParam("key2") String key2,
@PathParam("key3") String key3,
回答by Paul Samsotha
Might be a good opportunity to rethink this design. By using /s, we are in a way signifying, with each /that we are trying to locate a different resource. Key/Value pairs (in the context of the URL) are mainly for query parameters or matrix parameters.
可能是重新思考这种设计的好机会。通过使用/s,我们在某种程度上表示,/我们正在尝试定位不同的资源。Key/Value 对(在 URL 的上下文中)主要用于查询参数或矩阵参数。
If /property/{uuid}is the path to a main resource, and we just want to offer some parameters to the client for accessing this resource, then we could allow matrix parameters or query parameters
如果/property/{uuid}是主资源的路径,而我们只想提供一些参数给客户端访问这个资源,那么我们可以允许矩阵参数或查询参数
Matrix Parameters(in a request url) will look something like
矩阵参数(在请求 url 中)看起来像
/12345;key1=value1;key2=value2;key3=value3
A resource method to obtain the values might look something like
获取值的资源方法可能类似于
@GET
@Path("/property/{uuid}")
public Response getMatrix(@PathParam("uuid") PathSegment pathSegment) {
StringBuilder builder = new StringBuilder();
// Get the {uuid} value
System.out.println("Path: " + pathSegment.getPath());
MultivaluedMap matrix = pathSegment.getMatrixParameters();
for (Object key : matrix.keySet()) {
builder.append(key).append(":")
.append(matrix.getFirst(key)).append("\n");
}
return Response.ok(builder.toString()).build();
}
- See
PathSegment
Query Parameters(in a request url) might look something like
查询参数(在请求 url 中)可能类似于
/12345?key1=value1&key2=value2&key3=value3
A resource method to obtain the values might look something like
获取值的资源方法可能类似于
@GET
@Path("/property/{uuid}")
public Response getQuery(@PathParam("uuid") String uuid,
@Context UriInfo uriInfo) {
MultivaluedMap params = uriInfo.getQueryParameters();
StringBuilder builder = new StringBuilder();
for (Object key : params.keySet()) {
builder.append(key).append(":")
.append(params.getFirst(key)).append("\n");
}
return Response.ok(builder.toString()).build();
}
- See
UriInfo
- 看
UriInfo
The difference is that Matrix parameters can be embedded into path segments, while query parameters must be placed at the end of the URL. You can also notice a little difference in syntax.
不同的是Matrix参数可以嵌入到路径段中,而查询参数必须放在URL的末尾。您还可以注意到语法上的一些差异。
Some Resources
一些资源
- Query String (Wikipedia)
- When to use query parameters versus matrix parameters?
- URL matrix parameters vs. request parameters
UPDATE
更新
Also looking at the PUTin you method signature, it appears you are trying update a resource using the path as the values for which you are trying to update, as I don't see any parameters in your method for an entity body. When PUTting, you should be sending the representation in the the entity body, not as as path segments orparameters.
同时查看PUT方法签名,您似乎正在尝试使用路径作为您尝试更新的值来更新资源,因为我在您的方法中没有看到实体主体的任何参数。PUTting 时,您应该在实体主体中发送表示,而不是作为路径段或参数。
回答by edubriguenti
A workaround:
解决方法:
@Path("/foo/bar/{other: .*}
public Response foo(@PathParam("other") VariableStrings vstrings) {
String[] splitPath = vstrings.getSplitPath();
}
VariableStrings class:
变量字符串类:
public class VariableStrings {
private String[] splitPath;
public VariableStrings(String unparsedPath) {
splitPath = unparsedPath.split("/");
}
}
Path segment sequence to vararg array in JAX-RS / Jersey?
JAX-RS / Jersey 中可变参数数组的路径段序列?
Another example where you map the optional parameter to a Map:
将可选参数映射到 Map 的另一个示例:
@GET
@ Produces({"application/xml", "application/json", "plain/text"})
@ Path("/location/{locationId}{path:.*}")
public Response getLocation(@PathParam("locationId") int locationId, @PathParam("path") String path) {
Map < String, String > params = parsePath(path);
String format = params.get("format");
if ("xml".equals(format)) {
String xml = "<location<</location<<id<</id<" + locationId + "";
return Response.status(200).type("application/xml").entity(xml).build();
} else if ("json".equals(format)) {
String json = "{ 'location' : { 'id' : '" + locationId + "' } }";
return Response.status(200).type("application/json").entity(json).build();
} else {
String text = "Location: id=" + locationId;
return Response.status(200).type("text/plain").entity(text).build();
}
}
private Map < String, String > parsePath(String path) {
if (path.startsWith("/")) {
path = path.substring(1);
}
String[] pathParts = path.split("/");
Map < String, String > pathMap = new HashMap < String, String > ();
for (int i = 0; i < pathParts.length / 2; i++) {
String key = pathParts[2 * i];
String value = pathParts[2 * i + 1];
pathMap.put(key, value);
}
return pathMap;
}

