gpt4 book ai didi

http - 使用 JAX-RS 的 "fake"DELETE 和 PUT 方法的最佳方法是什么?

转载 作者:可可西里 更新时间:2023-11-01 17:04:13 26 4
gpt4 key购买 nike

我刚开始使用 Jersey为我的网站创建一个 RESTful API。与我自己对 Java 中的 RESTful 服务的支持相比,这是一个美妙的变化。我似乎无法弄清楚的一件事是如何“伪造”DELETE 和 PUT 方法。

Jersey 支持注解@PUT 和@DELETE,但是许多负载均衡器不允许这些方法通过。过去,我依赖于在 POST 请求中定义自定义 HTTP header (例如 x-method-override: DELETE)和“隧道”的能力。

有没有人找到一种方法来将使用 Jersey/JAX-RS 注释的方法绑定(bind)到自定义 header ?或者,是否有更好的方法解决缺少对 PUT 和 DELETE 的支持?

最佳答案

这就是我决定如何在我的 API 中处理这种情况。它相对简单,不需要太多额外的编码。为了说明,请考虑地址的 RESTful API:

@Path("/address")
public class AddressService {

@GET
@Produces("application/xml")
public StreamingOutput findAll() { ... }

@POST
@Produces("application/xml")
@Consumes("application/x-www-form-urlencoded")
public StreamingOutput create(...) { ... }

//
// This is the alternative to a "PUT" method used to indicate an "Update"
// action. Notice that the @Path expects "/id/{id}" which allows
// us to bind to "POST" and not get confused with a "Create"
// action (see create() above).
//
@POST
@Produces("application/xml")
@Consumes("application/x-www-form-urlencoded")
@Path("/id/{id}")
public StreamingOutput update(@PathParam("id") Long id, ...) { ... }

//
// This is the typical "GET" method with the addition of a check
// for a custom header "x-method-override" which is designed to
// look for inbound requests that come in as a "GET" but are
// intended as "DELETE". If the methodOverride is set to "DELETE"
// then the *real* delete() method is called (See below)
//
@GET
@Produces("application/xml")
@Path("/id/{id}")
public StreamingOutput retrieve(
@PathParam("id") Long id,
@HeaderParam("x-method-override") String methodOverride)
{
if (methodOverride != null && methodOverride.equalsIgnoreCase("DELETE")) {
this.delete(id);
}

...
}


//
// This is the typical "DELETE" method. The onlything special about it is that
// it may get invoked by the @GET equivalent is the "x-method-override" header
// is configured for "DELETE"
//
@DELETE
@Produces("application/xml")
@Path("/id/{id}")
public StreamingOutput retrieve(@PathParam("id") Long id) { ... }

关于http - 使用 JAX-RS 的 "fake"DELETE 和 PUT 方法的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1484186/

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