Expand my Community achievements bar.

Get Cookie Example of AEM Servlet and Sling Model | AEM Community Blog Seeding

Avatar

Administrator

BlogImage.jpg

Get Cookie Example of AEM Servlet and Sling Model by SourceCode

Abstract

In this short article, we will show two code examples; for example, one will be showcasing how cookies values can be accessed for an AEM Servlet, and for example two, Sling Model.

1. AEM Servlet Get Cookie Example

package com.sourcedcode.core.servlet;

import com.cat.wcm.core.util.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.osgi.service.component.annotations.Component;

import javax.servlet.Servlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_PATHS;

@Component(
service = { Servlet.class },
property = {
SLING_SERVLET_PATHS + "=/bin/getCookieExample"
}
)
public class GetCookieServletExample extends SlingAllMethodsServlet {

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
Cookie myCookie = getCookie(request, "myCookie");
String myCookieValue = "";
if (myCookie != null && !myCookie.getValue().isBlank()) {
myCookieValue = myCookie.getValue();
}

// server response
response.setStatus(200);
response.setContentType("application/json");

JSONObject jsonResponse = new JSONObject();
jsonResponse.put("myCookie", myCookieValue);
response.getWriter().write(jsonResponse.toString());
}

// 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;
}
}
}
}

Read Full Blog

Get Cookie Example of AEM Servlet and Sling Model

Q&A

Please use this thread to ask the related questions.



Kautuk Sahni
0 Replies