No Servlets Required: Exporting Data with Sling Models

Published on by Dan KlcoPicture of Me Dan Klco

Since version 1.3.0 of Sling Models, which was released in November 2016 and is available in AEM 6.3+, the Apache Sling team introduced a new capability to directly export models as a Java Servlet. I finally have a chance to use this new feature and I found it reduced the amount of boilerplate code I had to write by at least half. Traditionally, to expose data in a Sling Model to JSON you had to use a tool like Gson to serialize it and write a Servlet to expose an endpoint. 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. When the Model is loaded into Apache Sling, it automatically registers a Servlet corresponding to the model. allowing you to zero Servlet code access a JSON representation of the model. That's super cool!