gpt4 book ai didi

Java REST API 查询注释

转载 作者:行者123 更新时间:2023-12-01 09:07:59 26 4
gpt4 key购买 nike

我目前正在尝试向我的 REST API 添加新功能。

基本上,我想添加将查询参数添加到路径末尾的功能,并将其转换为所有查询选项的映射。

我当前的代码允许我做类似的事情

localhost:8181/cxf/check/
localhost:8181/cxf/check/format
localhost:8181/cxf/check/a/b
localhost:8181/cxf/check/format/a/b

这将使用所有 @pathparam 作为字符串变量来生成响应。

我现在想做的是添加:

localhost:8181/cxf/check/a/b/?x=abc&y=def&z=ghi&...
localhost:8181/cxf/check/format/a/b/?x=abc&y=def&z=ghi&...

然后我会生成一个 map ,可以与路径参数一起使用来构建响应

x => abc
y => def
z => ghi
... => ...

我在想这样的事情[如下],但是 @QueryParam 似乎只处理一个键值,而不是它们的映射。

@GET
@Path("/{format}/{part1}/{part2}/{query}")
Response getCheck(@PathParam("format") String format, @PathParam("part1") String part1, @PathParam("part2") String part2, @QueryParam("query") Map<K,V> query);

下面是我当前的界面代码。

@Produces(MediaType.APPLICATION_JSON)
public interface RestService {

@GET
@Path("/")
Response getCheck();

@GET
@Path("/{format}")
Response getCheck(@PathParam("format") String format);

@GET
@Path("/{part1}/{part2}")
Response getCheck(@PathParam("part1") String part1,@PathParam("part2") String part2);

@GET
@Path("/{format}/{part1}/{part2}")
Response getCheck(@PathParam("format") String format, @PathParam("part1") String part1, @PathParam("part2") String part2);

}

最佳答案

QueryParam("") myBean 允许获取注入(inject)的所有查询参数。还删除最后一个 {query} 部分

@GET
@Path("/{format}/{part1}/{part2}/")
Response getCheck(@PathParam("format") String format, @PathParam("part1") String part1, @PathParam("part2") String part2, @QueryParam("") MyBean myBean);

public class MyBean{
public void setX(String x) {...}
public void setY(String y) {...}
}

您也可以不声明参数并解析 URI。如果您可以接受非固定参数,则此选项可能很有用

 @GET
@Path("/{format}/{part1}/{part2}/")
public Response getCheck(@PathParam("format") String format, @PathParam("part1") String part1, @PathParam("part2") String part2, @Context UriInfo uriInfo) {
MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
String x= params.getFirst("x");
String y= params.getFirst("y");
}

关于Java REST API 查询注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41100241/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com