122015Apr

Send Multiple Cookies As Part Of Response In Jersey Rest API

Jersey

Jersey RESTful Web Services framework is open source, production quality, framework for developing RESTful Web Services in Java that provides support for JAX-RS APIs and serves as a JAX-RS (JSR 311 & JSR 339) Reference Implementation.

Sending Multiple Cookies

While using REST API sometimes there is requirement to to maintain the cookies or session between the client and server so to maintain this you need to pass all the cookies as part of request as well as part of response. So here is the little code snippet to send cookies as part of response in Jersey Rest API.

//Create an instance of Response Builder with OK response.
ResponseBuilder rb = Response.OK();

//Setting One Cookie
rb.cookie(new Cookie("Key","Value"));

//Setting multiple cookies in response reading from cookieMap
for (Map.Entry<String, String> entry : cookieMap.entrySet()) {

    rb.cookie(new Cookie(entry.getKey() , entry.getValue()));

}

//building and returning response object
return rb.build();

Above In the code cookieMap is the map container of cookies where key is cookie name and key’s value is cookie value.