【问题标题】:Jersey REST And PathParam Regular ExpressionsJersey REST 和 PathParam 正则表达式
【发布时间】:2013-11-18 10:56:19
【问题描述】:

我正在尝试使用 Jersey 开发 REST Web 服务。我的要求是能够根据传递的 PatParam 参数访问 Web 服务并返回数据。到目前为止,我的网络服务如下:

@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes({ "application/xml", "application/json", "application/x-www-form-urlencoded" })
@Path("/1.0/people{extension:(.json)*}/{personId:([^/]+?)?}{entityExtension:(.json)*}")
public String getLocation(@PathParam("extension") String extension, @PathParam("personId") String personId,@PathParam("entityExtension") String entityExtension)
{
    if ((personId==null ||personId.equals("")) && (extension == null || extension.equals("")))
        return "No Id, and no extension";
    else
        return "personId= "+personId + ", extension= " + extension+", entityExtension= "+entityExtension;
}

考虑到上面的代码,我想要实现的是:

http://localhost:8080/Jersey/RestService/1.0/people.json

应该以“json”格式返回所有人的列表(因此是 .json 扩展名)

现在,我希望能够通过简单地输入人的 ID 来获取特定人的信息,并根据扩展名在 json/xml 中返回该人的信息:

http://localhost:8080/Jersey/RestService/1.0/people/Mouhammed89.json

使用上面的 URL,我应该返回 personId: Mouhammed89 的信息,并以 json 格式返回信息。

我知道我的问题在于我正在使用的正则表达式,所以我非常感谢在创建它们方面的帮助。

【问题讨论】:

    标签: java regex rest jersey-1.0 path-parameter


    【解决方案1】:

    恕我直言,容器 (List) 和项目 (Person) URL 应分开处理。 而且您不需要显式的 .json 前缀来返回 JSON 响应,只需 API 级别的注释就足够了。

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/1.0/people") //no need for .json suffix as API only return JSON format
    public List<String> allLocations(..){ //jackson etc. will convert return type to json string 
    ..
    }
    
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/1.0/people/{personId: \\d+}")//digits only
    public String getLocation(..){ //jackson etc. will convert return type to json string 
    ..
    }
    

    【讨论】:

    • 谢谢苛刻。我依赖 PathParameter 来决定返回哪种格式的原因是我希望某些客户端向我发送请求而不在标头中向我发送“Accept”,在这种情况下我不知道要哪种格式回到他们身边。这就是我们决定在 URL 中包含扩展名的原因。
    • 好的,我认为这应该有助于您将扩展映射到media-typezcox.wordpress.com/2009/08/11/uri-extensions-in-jersey
    • 感谢 Harsh,这太棒了。我最终使用了两种不同的 Web 服务方法:一种获取所有人的列表,另一种获取特定人员的信息。我还实现了自定义 PackagesResourceConfig,它帮助我在 URL 本身中传递了我想要的扩展名,Jersey 最终为我做了 XML/JSON 映射 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多