Creating a cookie inside jax-rs endpoint

I have a jax-rs endpoint. The purpose of the endpoint is to authorize the user. I need to login to a cookie. I have mentioned the related part of my code below.

public Response authorize(@Context HttpServletRequest request) throws URISyntaxException {
     if (authnResult.isAuthenticated()) {
     //TODO create a cookie to maintain login state
                        Cookie authCookie = new Cookie(FrameworkConstants.COMMONAUTH_COOKIE, "test");
                        authCookie.setMaxAge(5 * 60);



This is my first time creating cookies. I followed some tutorials. In these tutorials, he added the generated cookie to the response. But inside the endpoint, I cannot access the answer. So how can I create a cookie? Please advise me.

Updated code:

public Response authorize(@Context HttpServletRequest request) throws URISyntaxException {
    NewCookie cookie = new NewCookie("CookieName","CookieValue");
                    Response.ResponseBuilder builder = Response.ok("Cool Stuff");
    Cookie[] cookies = request.getCookies();


I need to know how to access the newly created cookie.


source to share

1 answer

You can create

. There are many different constructors, just go through the API docs.

Then you can add cookies via ResponseBuilder#cookie(NewCookie)

. For example:

public Response getCookie() {
    NewCookie cookie = new NewCookie("Name", "Value", "path", "domain",
                                     "comment", 300, true, true);
    ResponseBuilder builder = Response.ok("Cool Stuff");


UPDATE (with complete example)

public class CookieResource {

    public Response getCookie(@CookieParam("A-Cookie") String cookie) {
        Response response = null;
        if (cookie == null) {
            response = Response.ok("A-Cookie: Cookie #1")
                    .cookie(new NewCookie("A-Cookie", "Cookie #1"))
            return response;
        } else {
            String cookieNum = cookie.substring(cookie.indexOf("#") + 1);
            int number = Integer.parseInt(cookieNum);
            String updatedCookie = "Cookie #" + number;
            response = Response.ok("A-Cookie: " + updatedCookie)
                    .cookie(new NewCookie("A-Cookie", updatedCookie))
            return response;


After 38 queries, you can see the result. I used Firefox Firebug plugin . You can see the sent cookie # 37 and return cookie # 38

enter image description here

If you need help trying to access the cookie from the client (as pointed out in your comment) this might be appropriate for another SO question. Maybe not to discuss this discussion as it will rely on a different technology. If this is not what you are looking for, perhaps a better explanation of what you are trying to accomplish will help.



All Articles