【问题标题】:Java REST API Query annotationJava REST API 查询注解
【发布时间】:2016-12-12 11:50:40
【问题描述】:

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

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

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

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,它可以与 pathparam 一起使用来构建响应

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

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

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

}

【问题讨论】:

    标签: java web-services rest cxf javax.ws.rs


    【解决方案1】:

    QueryParam("") myBean 允许获取所有注入的查询参数。同时删除最后的{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");
    }
    

    【讨论】:

    • @Context 是我一直在看的我喜欢的东西(因为它构建了一个地图)但是我在让它工作时遇到了问题(可能只需要再看几个例子。)这允许我使用 @Path("/{format}/{part1}/{part2}/") 或者我必须将其留空,然后稍后从 UriInfo 中提取路径?
    • 你可以同时使用@PathParam@Context UriInfo。我已在答案中包含完整示例
    • 谢谢,我会尽快测试谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多