سؤال

لقد بدأت للتو في استخدام جيرسي لإنشاء API مريح لموقعي. إنه تغيير رائع من الاضطرار إلى الدعم الخاص بي للحصول على خدمات مريحة في جافا. شيء واحد لا يمكن أن يبدو أن معرفة كيفية "وهمية" حذف ووضع طريقة.

يدعم جيرسي التعليقات التوضيحية Dute و DELETE، إلا أن العديد من موازنات التحميل لن يسمحوا بهذه الأساليب. في الماضي، اعتمدت على القدرة على تحديد رأس HTTP مخصص (مثل تجاوز أسلوب X: حذف) و "الأنفاق" ضمن طلب المشاركة.

هل وجد أي شخص طريقة لربط طريقة باستخدام التعليقات التوضيحية جيرسي / JAX-RS إلى رؤوس مخصصة؟ بدلا من ذلك، هل هناك طريقة أفضل حول عدم وجود دعم لوضع وحذف؟

هل كانت مفيدة؟

المحلول

حسنا هنا كيف قررت التعامل مع الوضع داخل واجهة برمجة التطبيقات الخاصة بي. انها بسيطة نسبيا ولا تتطلب الكثير من الترميز الإضافي. لتوضيح النظر في 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) { ... }

}

نصائح أخرى

انها ليست حقا الراحة بعد الآن، ولكن في وضع مماثل حددنا نشر / جمع / أن تكون إدراج (كالمعتاد) أو Post / Collection / {ID} لتكون تحديث أو نشر / جمع / {ID} دون حذف الجسم.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top