关于 REST 中 http 方法重载的建议

发布于 2024-09-16 06:22:34 字数 642 浏览 1 评论 0原文

我在 @Path 中使用了正则表达式来实现重载,起初我认为它非常简洁,但重载方法通常不是一个好的做法。这同样适用于 RESTful Web 服务吗?有没有更好的方法使用 JAX-RS 来实现这一目标?

所以我现在可以通过 /project/ProjectNumber1000 或 /project/12345 调用我的 getProject REST 服务

@Path("/project")
public class ProjectPropertiesResource
{
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/{name : [a-zA-Z]+}")
    public Response getProjectPropertiesByName(@PathParam("name") String name)
    {
         ...
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/{id : \\d+}")
    public Response getProjectPropertiesById(@PathParam("id") long id)
    {
         ...
    }
}

I've used a regular expression in @Path to achieve overloading and at first I thought it was really neat, but overloading methods is usually not good practice. Does the same apply to RESTful web services? Is there a better way to achieve this using JAX-RS?

So I can now call my getProject REST service by /project/ProjectNumber1000 or /project/12345

@Path("/project")
public class ProjectPropertiesResource
{
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/{name : [a-zA-Z]+}")
    public Response getProjectPropertiesByName(@PathParam("name") String name)
    {
         ...
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/{id : \\d+}")
    public Response getProjectPropertiesById(@PathParam("id") long id)
    {
         ...
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乖不如嘢 2024-09-23 06:22:34

但是,您可以这样做,只有一个重载实际上应该返回带有 200 的响应正文。其他重载应该返回 303 重定向到返回正文的 URI。

这将确保缓存仅拥有该资源的一份副本,如果您对主 URI 执行 PUT 或 POST 操作,您将使该一份副本失效。否则,由于缓存中存在不同的版本,您可能会开始获得不一致的结果。

You can do it, however, only one of the overloads should actually return response body with a 200. The other overloads should return a 303 redirect to the URI that returns the body.

This will ensure that caches only have one copy of the resource and if you do PUT or POST on the main URI you will invalidate the one copy. Otherwise, you can start to get inconsistent results due to different versions existing in the cache.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文