Here, I am going to explain to you how to export page data as a JSON format using sling servlet, this is developed on AEM 6.3, so you need to have below OSGI dependencies in your pom.xml file, if you created your project using AEM project archetype version 12 then you don’t  need to add these, by default it comes

Step 1: Add dependencies

                <plugin>
                    <groupId>org.apache.felix</groupId>
                    <artifactId>maven-bundle-plugin</artifactId>
                    <version>3.3.0</version>
                    <inherited>true</inherited>
                </plugin>
 <!-- OSGi Dependencies -->
            <dependency>
                <groupId>org.osgi</groupId>
                <artifactId>osgi.core</artifactId>
                <version>6.0.0</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.osgi</groupId>
                <artifactId>osgi.cmpn</artifactId>
                <version>6.0.0</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.osgi</groupId>
                <artifactId>osgi.annotation</artifactId>
                <version>6.0.1</version>
                <scope>provided</scope>
            </dependency>

Step 2: Import packages

You need to import below packages in your servlet.class file

import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;

Step 3: Create a  servlet

Here, I am not using separate class to load configurations, if you have so many properties to configure then I would recommend you to create a separate class and load it using @Designate annotation, want to know how to use @Designate annotation then refer my other article OSGI annotations – service
The below servlet reads title and path of all the child pages of configured root page and export it using JSON format, as we are exporting content as JSON format so we must add response.setContentType(“application/json”);
The buildLinks() method read all the child pages of configured page and populate list collection with the page information
Finally, I am using Google Gson to convert list collection object into a JSON string

package com.aem.toolkit.core.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Optional;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import com.aem.toolkit.core.models.PageBean;
import com.day.cq.wcm.api.Page;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@Component(service = Servlet.class, property = { "sling.servlet.extensions=json",
		"sling.servlet.paths=/bin/jsonservlet",
		"sling.servlet.methods=get" }, configurationPolicy = ConfigurationPolicy.REQUIRE, immediate = true
)
@Designate(ocd = JsonServlet.Configurations.class)
public class JsonServlet extends SlingSafeMethodsServlet {
	private static final long serialVersionUID = 1L;
	public static java.util.List<PageBean> links = new ArrayList<PageBean>();
	private String nodePath;
	Resource resource;
	@ObjectClassDefinition(name = "JSON Demo Servlet")
	public @interface Configurations {
		@AttributeDefinition(name = "Enter Path", description = "Page or node path")
		String getPath();
	}
	@Override
	protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
			throws ServletException, IOException {
		if (nodePath != null) {
			ResourceResolver resourceResolver = request.getResourceResolver();
			resource = resourceResolver.resolve(nodePath);
			PrintWriter out = response.getWriter();
			response.setContentType("application/json");
			out.write(buildLinks());
			out.flush();
		}
	}
	public String buildLinks() {
		if (resource != null) {
			Iterator<Resource> linkResources = resource.listChildren();
			linkResources.forEachRemaining(res -> populateModel(res).ifPresent(links::add));
		}
       String jsonData = buildJson();
       return jsonData;
	}
	public Optional<PageBean> populateModel(Resource resource) {
		PageBean link = new PageBean();
		Page page = resource.adaptTo(Page.class);
		if (page != null) {
			link.setTitle(page.getTitle());
			link.setPath(page.getPath());
		}
		return Optional.of(link);
	}
	public String buildJson() {
		GsonBuilder builder = new GsonBuilder();
		builder.excludeFieldsWithoutExposeAnnotation();
		Gson gson = builder.create();
		return gson.toJson(links);
	}
	@Activate
	@Modified
	protected void Activate(Configurations config) {
		nodePath = config.getPath();
	}
}

Finally, you should see the output something like below
osgi-annotations-servlet-json

Download Code

[signinlocker] json export [/signinlocker]

By coderss

Leave a Reply

Your email address will not be published. Required fields are marked *