在CXF restful webservice中处理动态查询参数

时间:2016-03-07 14:24:20

标签: java web-services rest cxf cxf-client

我想在CXF RESTful服务中处理动态查询参数。

我担心的是服务端,我不知道请求附带的参数/密钥名称的数量。能不能让我知道我们如何处理这种情况/场景。

例如,我的客户端代码如下所示

Map<String, String> params = new HashMap<>();
params.put("foo", "hello");
params.put("bar", "world");

WebClient webClient = WebClient.create("http://url"); 
for (Entry<String, String> entry : params.entrySet()) {
    webClient.query(entry.getKey(), entry.getValue());
}

Response res = webClient.get(); 

以下代码适用于我,

public String getDynamicParamter(@Context UriInfo ui){
    System.out.println(ui.getQueryParameters());
    MultivaluedMap<String, String> map = ui.getQueryParameters();
    Set keys=map.keySet();
    Iterator<String > it = keys.iterator();
    while(it.hasNext()){
        String key= it.next();
        System.out.println("Key --->"+key+"  Value"+map.get(key).toString());
    }
    return "";

}

但是,请您告诉我以下内容,

  1. 是否是标准方式?
  2. 并且,还有其他方法可以实现吗?
  3. CXF版本:3.1.4

1 个答案:

答案 0 :(得分:1)

UriInfo

获取查询参数

正如您已经猜到的,UriInfo API中有一些方法可以为您提供查询参数:

可以使用UriInfo注释在资源类成员中注入@Context

@Path("/foo")
public class SomeResource {

    @Context
    private UriInfo uriInfo;

    @GET
    public Response someMethod() {
        MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
        ...
    }
}

可以在方法参数中注入:

@GET
public Response someMethod(@Context UriInfo uriInfo) {
    MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
    ...
}

要获取未解析的查询字符串,请执行以下操作:

@GET
public Response someMethod(@Context UriInfo uriInfo) {
    String query = uriInfo.getRequestUri().getQuery();
    ...
}

HttpServletRequest

获取查询参数

您可以通过将HttpServletRequest注入@Context注释来获得类似的结果,就像上面提到的UriInfo一样。以下是一些有用的方法:

相关问题