Highlighted

Create a Servlet to read a property from Multiple pages

svijay2980

21-11-2018

Hi All,

I have a requirement to create a Sling Servlet that will get the root path of my website. It should loop through the children pages and read a particular property and expose the page url and the property as JSON. I want this to be displayed in the frontend by creating a HTL component that will get the data from this servlet. Could you please suggest the best approach that can be followed to accomplish this?


Replies

Highlighted

smacdonald2008

21-11-2018

This is quite possible with HTL and Sling Models, You would need to create a BEAN on the Java side to store all props. THen have logic in Java to read all of the child pages and read the props that you want. I would look at using JCR SQL2 to perform the query:

String sqlStatement = "select * from [cq:Page] where isdescendantnode('/content/we-retail') "

Then iterate through the result set and get the props you want. in the Java - use GSON (or another JSON Java lib) to construct the JSON too.

Highlighted

svijay2980

21-11-2018

That's quite alright but my requirement is to have a Servlet that does this. Is it possible to get the values from a Sling servlet and parse it to be used in HTL? Thanks

Highlighted

smacdonald2008

21-11-2018

Java logic is what matters. You can call a Servlet or a use a Sling Model. Jusy different ways to invoke Java business logic in a OSGi bundle.

I am working on an example to do this.

Highlighted

lokeshb93001514

21-11-2018

Why only a servlet? Best way is to write a sling model and call the service from that where the service will return the object with the necessary properties.

Highlighted

smacdonald2008

21-11-2018

Also be aware that looping through all the pages in a result set will be bad performance - esp if you want to display in a component. If you need to get that data for some reason - it makes more sense to run in a workflow - where it will not impact performace of your site.

Highlighted

smacdonald2008

21-11-2018

I did testing - even with a smaller page range - it will still take time to progress all pages in the result set. See:

.Size.png

Highlighted

svijay2980

21-11-2018

I'm working on an application as part of an assignment which will have a maximum of 5-6 pages. So it's not an issue if performance is affected.

Highlighted

svijay2980

21-11-2018

I'm working on an application as part of an assignment and the Servlet was already provided. My job is to read the JSON received as response from the Servlet and display it on the page using HTL.