¿Cuál es la mejor manera de “falso” DELETE y PUT métodos utilizando JAX-RS?
-
18-09-2019 - |
Pregunta
He empezado a usar Jersey para crear una API REST para mi sitio. Es un maravilloso cambio de tener que rodar mi propio apoyo a los servicios REST en Java. Una cosa que me parece que no puede averiguar cómo es "falso" un método DELETE y PUT.
Jersey soporta las anotaciones @PUT y @DELETE, sin embargo muchos equilibradores de carga no permitirá que estos métodos a través. En el pasado he confiado en la capacidad de definir un encabezado HTTP personalizado (por ejemplo, x-método-override: DELETE). Y "túnel" dentro de una solicitud POST
¿Alguien ha encontrado una manera de obligar a un método que utiliza Jersey / JAX-RS anotaciones de cabeceras personalizadas? Por otra parte, hay una mejor manera alrededor de la falta de apoyo para PUT y DELETE?
Solución
Bueno, aquí es cómo me he decidido a manejar la situación dentro de mi API. Su relativamente simple y no requiere mucha codificación adicional. Para ilustrar considerar una API REST de Dirección:
@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) { ... }
}
Otros consejos
No es realmente DESCANSO más, pero en una situación similar que define la POST / recolección / a insertar (como de costumbre), POST / colección / {id} sea la actualización, POST / colección / {id} sin cuerpo para estar eliminar.