开发者

Changing content type in jax-rs REST service

Forgive me, but I may not be familiar with all the lingo necessary to ask this question properly.

I'm working on a fairly simple REST web service in Java using the org.apache.cxf.jaxrs.ext implementation of jax-rs. The method header is like this:

@GET
@Path("json/{fullAlias}")
@Produces({"application/json"})
public String json(@PathParam("fullAlias") String fullAlias, @Context MessageContext req)

where MessageContext is org.apache.cxf.jaxrs.ext.MessageContext.

There are two things I'm trying to accomplish that I can't seem to figure out:

  1. Change the content-type if certain conditions are met (e.g. for an error)
  2. Change the status code of the response

I've tried using changing the response by accessing it through the MessageContext:

HttpServletResponse response = req.getHt开发者_StackOverflow中文版tpServletResponse();
response.setContentType("text/plain")
response.setStatus("HttpServletResponse.SC_BAD_REQUEST);

But these changes have no bearing on the response sent; with or without the @Produces annotation, setting the content type inside the method doesn't affect the actual content type (With the annotation, it of course returns "application/json", without it defaults to "text/html").

I am returning a simple String as the body. I've entertained trying to return a javax.ws.rs.core.Response object to do what I want, but I don't know much about it.

How would I change the content type and/or the status codes from inside this method?


One approach is to throw a WebApplicationException, as described by Pace, which will work if you are looking to specifically handle an error condition. If you are looking to be able to change your content at any time for any reason, then you will want to take a look at returning a Response as the result of your service method rather than a String. Returning a Response gives you the greatest amount of control over how your service responds to the client request (it does require more code than returning a simple string).

Here is an example of how you would can make use of the Response object:

@GET
@Path("json/{fullAlias}")
public Response json(@PathParam("fullAlias") String fullAlias, @Context MessageContext req) {
    ...
    if (success) {
        ResponseBuilder rBuild = Response.ok(responseData, MediaType.APPLICATION_JSON);
        return rBuild.build();
    }
    else {
        ResponseBuilder rBuild = Response.status(Response.Status.BAD_REQUEST);
        return rBuild.type(MediaType.TEXT_PLAIN)
                     .entity("error message")
                     .build();
    }    
}


I'm not sure if it's the best approach but I've done the following to solve your question #1.

public WebApplicationException createStatusException(String statusMessage) {
    ResponseBuilder rb = Response.noContent();
    rb = rb.type(MediaType.TEXT_PLAIN);
    rb = rb.status(Status.BAD_REQUEST);
    rb = rb.entity(statusMessage);
    return new WebApplicationException(rb.build());
}

EDIT: I then threw the resulting WebApplicationException.


You can write your own Response Filter to change the content-type header.

@Provider
public class MimeAddingFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {
        responseContext.getHeaders().add("Content-Type", "image/png");
    }

}

This filter will add the "image/png" content-type header. You can also change or remove headers in JAX-RS response filters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜