views:

52

answers:

2

The JAX-RS implementation Jersey supports MVC style web applications through the Viewable class, which is a container for a template name and a model object. It is used like this:

@GET
public Viewable get() {
  return new Viewable("/index", "FOO");
}

I wonder how a status code could be returned with this approach. The above would implicitly return 200, but that wouldn't be appropriate in any case. Is there a way to set a status code explicitly?

A: 

Hmm you can create custom Response object in jersey thusly: this will return a 200:

@GET
public Response get() {
    URI uri=new URI("http://nohost/context");
    Viewable viewable=new Viewable("/index", "FOO");
    return Response.ok(viewable).build();
}

to return something different use this approach:

@GET
public Response get() {
    int statusCode=204;
    Viewable myViewable=new Viewable("/index","FOO");
    return Response.status(statusCode).entity(myViewable).build();
}

Hope that helped....

smeg4brains
+1  A: 

You will have to return a Response set up with the correct status code and headers containing your Viewable, e.g.:

@GET
public Response get() {
  return Response.status(myCode).entity(new Viewable("/index", "FOO")).build();
}
Moritz
Sometimes it's easier than you think!
deamon