JAX-RS — How to return JSON and HTTP status code together?

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;
}

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

I tried to use HttpServletResponse:

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

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

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?

14 Answers
14

Leave a Comment