Phoenix_uy
Phoenix_uy

Reputation: 3294

Cookie is not being created from servlet

I have a Sling Servlet that makes a doPost and doPut returning a json as the response.

In the code, I need to get a cookie and if that cookie doesn't exists I need to create it. My problem is that I'm doing a response.addCookie but then if I call the method again, the cookie is not present, so I'm not creating anything. What am I missing?

This is part of my code: Here's the method that stores (or updates) the cookie:

private SlingHttpServletResponse storeAppsCookie(SlingHttpServletRequest request, SlingHttpServletResponse response, String appsJsonFormat) {
        String username = getUsernameFromCookie(request);
        if(username.equals("")) return response;
        Cookie appsCookie = request.getCookie(this.appsCookieKey);
        if(appsCookie != null) {
            appsCookie.setValue(appsJsonFormat);

        } else {
            appsCookie = new Cookie(this.appsCookieKey, appsJsonFormat);
        }
        appsCookie.setMaxAge(30*24*60*60); //for 30 days
        appsCookie.setHttpOnly(true);
        response.addCookie(appsCookie);
        return response;
    }

Here's the final code in the doGet method:

String parsedContent = parseAppsToUpdate(request, appsArray);
            response = storeAppsCookie(request, response, parsedContent);
            response.setContentType("application/json");
            response.getWriter().write(userApps.toString());

Upvotes: 1

Views: 1044

Answers (1)

Phoenix_uy
Phoenix_uy

Reputation: 3294

I just found my answer. There's a cookie path that is missing in the code: appsCookie.setPath("/") With this setup, the cookie now is saved and I can see it on the browser side.

Upvotes: 1

Related Questions