JAX-RS — 如何同时返回 JSON 和 HTTP 状态代码? [英] JAX-RS — How to return JSON and HTTP status code together?

查看:22
本文介绍了JAX-RS — 如何同时返回 JSON 和 HTTP 状态代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写 REST Web 应用程序(NetBeans 6.9、JAX-RS、TopLink Essentials)并尝试返回 JSON HTTP 状态代码.我已准备好代码并在从客户端调用 HTTP GET 方法时返回 JSON.本质上:

I'm writing a REST web app (NetBeans 6.9, JAX-RS, TopLink Essentials) and trying to return JSON and HTTP status code. I have code ready and working that returns JSON when the HTTP GET method is called from the client. Essentially:

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

    // some code to return JSON ...

    return myJson;
}

但我想与 JSON 数据一起返回 HTTP 状态代码(500、200、204 等).

But I also want to return an HTTP status code (500, 200, 204, etc.) along with the JSON data.

我尝试使用 HttpServletResponse:

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

但这让浏览器认为这是一个真实"的 500,因此输出网页是一个常规的 HTTP 500 错误页面.

But this made the browser think it's a "real" 500 so the output web page was a regular HTTP 500 error page.

我想返回一个 HTTP 状态代码,以便我的客户端 JavaScript 可以根据它处理一些逻辑(例如,在 HTML 页面上显示错误代码和消息).这是可能的还是不应该将 HTTP 状态代码用于此类事情?

I want to return an HTTP status code so that my client-side JavaScript can handle some logic depending on it (to e.g. display the error code and message on an HTML page). Is this possible or should HTTP status codes not be used for such thing?

推荐答案

举个例子:

@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();
}

看看响应类.

请注意,您应该始终指定一个内容类型,尤其是在您传递多个内容类型时,但如果每条消息都将表示为 JSON,您只需使用 @Produces("application/json")

Note that you should always specify a content type, especially if you are passing multiple content types, but if every message will be represented as JSON, you can just annotate the method with @Produces("application/json")

这篇关于JAX-RS — 如何同时返回 JSON 和 HTTP 状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆