Alex Rivera | Logout

JAX-RS — How can I return a JSON and HTTP status code together?

Asked 2011-01-14T01:45:35.167
287

I'm writing a REST web application (NetBeans 6.9, JAX-RS, and TopLink Essentials) and trying to return JSON and HTTP status code. I have code ready and working that returns JSON content 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 content ...

    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 was 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 a thing?

Edit
Report

2 Answers

6

In case you want to change the status code because of an exception, with JAX-RS 2.0 you can implement an ExceptionMapper like this.

This handles this kind of exception for the whole application.

@Provider
public class UnauthorizedExceptionMapper implements ExceptionMapper<EJBAccessException> {

    @Override
    public Response toResponse(EJBAccessException exception) {
        return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
    }

}
answered 2013-05-19T19:57:23.077
5

JAX-RS has support for standard/custom HTTP codes. See ResponseBuilder and ResponseStatus, for example:

http://jackson.codehaus.org/javadoc/jax-rs/1.0/javax/ws/rs/core/Response.ResponseBuilder.html#status%28javax.ws.rs.core.Response.Status%29

Keep in mind that JSON information is more about the data associated with the resource/application. The HTTP codes are more about the status of the CRUD operation being requested (at least that is how it's supposed to be in RESTful systems).

answered 2011-01-14T03:51:08.050

Your Answer