We are setting a cookie through a model class:
ecs.setMaxAge(600);
response.addCookie(ecs);
I can see the cookie set in the Application cookies in the browser. However, when I try to retrieve this from the Servlet request.getCookie("ecs").getValue() I get a null pointer exception. This cookie is not being retrieved in the servlet.
Kindly help in figuring out what could be the issue.
Solved! Go to Solution.
Views
Replies
Total Likes
hi @pixislinger
can you check the path in the application cookies browser .Since you have not set it explicitely it would take the current path
You can set the path like below
cookie.setPath("/");
Then try accessing the servlet it should come up .
Also use the below snippet in case you want to iterate over the cookies and see if its coming
// extracted helper method
private Cookie getCookie(HttpServletRequest request, String cookieName) {
if (StringUtils.isBlank(cookieName)) {
return null;
} else {
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return null;
} else {
if (cookies.length > 0) {
Cookie[] var3 = cookies;
int var4 = cookies.length;
for(int var5 = 0; var5 < var4; ++var5) {
Cookie cookie = var3[var5];
if (StringUtils.equals(cookieName, cookie.getName())) {
return cookie;
}
}
}
return null;
}
}
}
https://sourcedcode.com/blog/aem/get-cookie-example-of-aem-servlet-and-sling-model
Hope it helps
hi @pixislinger
can you check the path in the application cookies browser .Since you have not set it explicitely it would take the current path
You can set the path like below
cookie.setPath("/");
Then try accessing the servlet it should come up .
Also use the below snippet in case you want to iterate over the cookies and see if its coming
// extracted helper method
private Cookie getCookie(HttpServletRequest request, String cookieName) {
if (StringUtils.isBlank(cookieName)) {
return null;
} else {
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return null;
} else {
if (cookies.length > 0) {
Cookie[] var3 = cookies;
int var4 = cookies.length;
for(int var5 = 0; var5 < var4; ++var5) {
Cookie cookie = var3[var5];
if (StringUtils.equals(cookieName, cookie.getName())) {
return cookie;
}
}
}
return null;
}
}
}
https://sourcedcode.com/blog/aem/get-cookie-example-of-aem-servlet-and-sling-model
Hope it helps
@pixislinger You need to set the cookie path as "/" while creating the cookie. Try below code to retrieve the cookie.
@pixislinger Do you find the suggestions from users useful? Please let us know if more information is required. Otherwise, please mark the answer as correct for posterity.
Views
Replies
Total Likes
Views
Likes
Replies