Expand my Community achievements bar.

Dive into Adobe Summit 2024! Explore curated list of AEM sessions & labs, register, connect with experts, ask questions, engage, and share insights. Don't miss the excitement.

How to read page content(only text) using Sling

Avatar

Level 2

Hi,

 

I have a requirement to read page content(text only) and club entire content as String.  I am able to read using JCR api below is the code snippet. Mostly we created content using Text component and title component so that's why I used those components only in search query.

 

public String getPageContent(SlingHttpServletRequest request) {
ResourceResolver resourceResolver = null;
Session session;
String stringJsonContent = null;
try {
resourceResolver = request.getResourceResolver();
if (resourceResolver != null && resourceResolver.isLive()) {
session = resourceResolver.adaptTo(Session.class);
Map<String, String> map = new HashMap<String, String>();
map.put("path",
"/content/mypage/jcr:content");
map.put("group.p.or", "true");
map.put("group.1_property", "sling:resourceType");
map.put("group.1_property.value", "mycomponents/components/content/text");
map.put("group.2_property", "sling:resourceType");
map.put("group.2_property.value", "mycomponents/components/content/title");
map.put("p.limit", "-1");
builder = resourceResolver.adaptTo(QueryBuilder.class);
// INvoke the Search query
Query query = builder.createQuery(PredicateGroup.create(map), session);
SearchResult sr = query.getResult();
String contentText = "";
// write out to the AEM Log file
LOGGER.info("Search Results: " + sr.getTotalMatches());
for (Hit hit : sr.getHits()) {
Resource textResource = hit.getResource();
ValueMap textProperties = textResource.adaptTo(ValueMap.class);
if (StringUtils.isBlank(textProperties.get("text", String.class))) {
if(StringUtils.isNotBlank(textProperties.get("jcr:title", String.class)))
contentText += " " + removeHtml(textProperties.get("jcr:title", String.class));
} else {
if(StringUtils.isNotBlank(textProperties.get("text", String.class)))
contentText += " " + removeHtml(textProperties.get("text", String.class));
}
}
}
} catch (Exception e) {
LOGGER.error("Bodybuilder DynamicMenu Exception : " + e);
}
}

 

Above code is working as expected. But I want to know Is there any other way to achieve above scenario instead of mentioning component names. Can we achieve using sling api.

 

Thanks,

Sathish

0 Replies