How to display a json response mapped pojo in sightly

747 Views Asked by At

I have a sling servlet that invokes a 3rd party api and fetches a json response. I have mapped the json response to a pojo class using Jackson. I now have to display this dynamically fetched and mapped response in sightly. How do i do that? I am stuck after the response mapping

3

There are 3 best solutions below

0
On BEST ANSWER

With the new version of Sling Models, you can directly expose a model as a Servlet by specifying a resource type and the selector to use in your model annotations. When the Model is loaded into Apache Sling, it automatically registers a Servlet corresponding to the model, allowing you to with nearly zero additional code, create a Servlet to access a JSON representation of the model. That’s super cool!

The above life makes your Life Easier!!

You can have all your objects in Sling Model. Since the sling model acts as a servlet You can make the AJAX call and get a real-time response.

Please refer to this document. https://blogs.perficient.com/2018/07/26/no-servlets-required-exporting-data-with-sling-models/

0
On

Assuming the JSON returned is arbitrary, the best thing to do is simply display it as a string. To do that, instead of mapping the JSON response to a POJO I would recommend adapting a Sling model to the response.

Then, you can set that Sling model to be the model in your sightly code, using data-sly-use.model, and in the Sling model constructor you can set the response value to an attribute of the sling model.

Then all you'd need to do is put that attribute in a ${} in the sightly html.

If the format/structure of the JSON isn't completely unknown, you could use the POJO in the sightly. Create some conditionals to test what attributes the POJO has, so you can put them into the sightly code.

0
On

The correct path is:

HTL/Sightly -> Sling Model -> OSGi Service -> External API

So you have to extract the code that fetches the data into an OSGi service.

But please secure your code that calls the external API. As example if the External API is not responding or is extremely slow, it could consume all available threads of AEM. Then AEM could be completely unusable. To secure it, you could use as Example a Semaphore.