[JAX-RS] 3 ways to get cookies

These are 3 ways to obtain cookies values in JAX-RS

[code language=”java”]
package com.example;

import javax.ws.rs.CookieParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.HttpHeaders;

@Path("/k")
public class CookieResource {

@GET
public String get(@CookieParam("customerId") int custId) {
return "Customer ID was " + custId;
}

@GET
@Path("object")
public String getAnother(@CookieParam("customerId") Cookie customerId) {
if (customerId != null) {
return customerId.getName();
}
return "no cookie named customerId";
}

@GET
@Path("headers")
public String getHeaders(@Context HttpHeaders headers) {
StringBuilder sb = new StringBuilder();
for (String name : headers.getCookies().keySet()) {
sb.append(name + " ");
}
return sb.toString();
}
}

[/code]

Leave a Reply

Your email address will not be published. Required fields are marked *