Expand my Community achievements bar.

Guidelines for the Responsible Use of Generative AI in the Experience Cloud Community.

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

Avatar

Administrator

BlogImage.jpg

Set 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 set for an AEM Servlet, and for example two, Sling Model.

1. AEM Servlet Set Cookie Example

package com.sourcedcode.core.servlets;

import com.cat.wcm.core.util.JSONObject;
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 java.io.IOException;

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

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

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
Cookie cookie = new Cookie("visitedCookieServletExample", "true");
cookie.setMaxAge(86400); // in seconds, 86400 = 24 hours.
response.addCookie(cookie);

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

JSONObject jsonResponse = new JSONObject();
jsonResponse.put("success", "true");
response.getWriter().write(jsonResponse.toString());
}
}
2. Sling Model Set Cookie Example

package com.sourcedcode.models.pages.page;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.SlingObject;

import javax.annotation.PostConstruct;
import javax.servlet.http.Cookie;

@Model(
adaptables = {SlingHttpServletRequest.class, Resource.class},
defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class ExampleModel {

@SlingObject
protected SlingHttpServletResponse response;

@PostConstruct
private void init() {
Cookie cookie = new Cookie("visitedExampleModel", "true");
cookie.setMaxAge(86400); // in seconds, 86400 = 24 hours.
response.addCookie(cookie);
}
}

Read Full Blog

Set Cookie Example of AEM Servlet and Sling Model

Q&A

Please use this thread to ask the related questions.



Kautuk Sahni
0 Replies