users@jersey.java.net

Setting Response location, code, etc..

From: Kevin Duffey <andjarnic_at_yahoo.com>
Date: Wed, 18 Jun 2008 19:30:21 -0700 (PDT)

Hey all,

We're starting to get a bit further with our project now. Actually got the RESTful web app deployed, and taking some calls.

I am confused on a few things tho. Is there a good doc that explains all the details of Jersey, including handling requests, setting response codes, headers, body, etc?

That said, I am using the NetBeans Jersey plugin, created a resource, my code looks something like:



@Path("test")
public class TestResource {

    @Context
    private UriInfo context;

    public TestResource() {
    }

    @GET
    @ProduceMime("application/xml")
    public String getXml() {
            return "test";
    }

    @POST
    @ConsumeMime("application/xml")
    public void postXml(String content) {
        // do something that creates something...

        // if all works, set status to 201, and set Location header to URL

       // if fail, set appropriate Status code.

       // HOW DO I SET RESPONSE CODE, BODY, LOCATION, HEADER INFO HERE?
    }
}


So in the above, I am sending in some XML as the content object to postXml. I do something with that XML, create something, etc. However, the method that the wizard creates does not set a return value. Where as HttpServeltResponse returns a response object that you can set headers on, etc... there seems to be no way after the call is made for me to indicate the response code, body (if I want to return one), and the Location header to return the proper URL to reference the created resource.

Same question applies to the GET method. I want to return a chunk of XML, or JSON maybe as part of the response Body, along with status code, etc. How do I manipulate the response that goes back. Looking at the UriInfo context variable doesnt appear to offer any methods or objects I can use to set response info.

Is it ok to do something like

@POST
@ConsumeMime("application/xml")
@ProduceMime("text/html")
public String someMethod(String contents){}

Such that I can handle xml input but return, html (or maybe json)? If so, to handle say xml, json or url-encoded form data in one call, and return json or xml back, how would I figure out the format coming in, and how do I specify the return format (again, how do I manipulate the response object so the Content-Type header going back is set based on the body going back).

Thanks all.