SORU
14 Ocak 2011, Cuma


JSON döndürür ve HTTP durum kodu birlikte?JAX-RS —

Uygulama (Eclipse 6.9, JAX-RS, Orijinal Temelleri) KALAN web yazma ve JSON dönmek için çalışıyorumveHTTP durum kodu. Kod HTTP GET yöntemini ne zaman döner JSON istemci adlı hazır ve çalışıyor. Aslında:

@Path("get/id")
@GET
@Produces("application/json")
public M_機械 getMachineToUpdate(@PathParam("id") String id) {

    // some code to return JSON ...

    return myJson;
}

Ama BenayrıcaHTTP durum kodu (500, 200, 204, vb.) geri dönmek istiyorum birlikte JSON veri.

HttpServletResponse kullanmaya çalıştım:

response.sendError("error message", 500);

Ama bu tarayıcı "" çıkış web sayfası normal bir HTTP 500 hata yani 500 sayfa. gerçek bir düşündürdü

İstemci tarafı JavaScript benim bazı mantık üzerine (örneğin bir HTML sayfasında Hata Kodu ve mesajı görüntülemek için) göre işleyebilir, bir HTTP durum kodu dönmek istiyorum. Bu mümkün veya HTTP durum kodları böyle bir şey için kullanılmamalıdır.

CEVAP
14 Ocak 2011, Cuma


İşte size bir örnek:

@GET
@Path("retrieve/{uuid}")
public Response retrieveSomething(@PathParam("uuid") String uuid) {
    if(uuid == null || uuid.trim().length() == 0) {
        return Response.serverError().entity("UUID cannot be blank").build();
    }
    Entity entity = service.getById(uuid);
    if(entity == null) {
        return Response.status(Response.Status.NOT_FOUND).entity("Entity not found for UUID: "   uuid).build();
    }
    String json = //convert entity to json
    return Response.ok(json, MediaType.APPLICATION_JSON).build();
}

Response sınıfı bir göz atın.

Her zaman, özellikle eğer birden fazla içerik türü geçirmeden içerik türünü belirtmeniz gerekir, ama eğer her mesaj JSON olarak temsil edilecek ise, sadece @Produces("application/json") ile açıklama yöntemi olduğunu unutmayın

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Joseph Herscher

    Joseph Hersc

    14 Mart 2007
  • KRQE

    KRQE

    6 AĞUSTOS 2007
  • SolidWorksTutoriels

    SolidWorksTu

    14 Kasım 2013