Coding

Create and use Servlet in AEM

What is a Servlet?

A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers.

Servlet declaration and registration

A servlet in AEM can be registered as OSGi service: you can extend SlingSafeMethodsServlet for read-only implementation or SlingAllMethodsServlet in order to implement all RESTFul operations.

You can declare servlet using static paths or resourceTypes (eventually combined with selectors and extensions): you can use both SlingServlet annotations or Component/Service/Properties.

Here two example combining the above options:

  • The  sling.servlet available configurations are:  paths,resourceTypes,selectors,extensions and  methods.
  • Either  sling.servlet.paths or the sling.servlet.resourceTypes property must be set, or the servlet is ignored.
  • sling.servlet.paths must be included in the Execution Paths: their setup is located in “Apache Sling Servlet/Script Resolver and Error Handler” entry of the Web Console Configuration (/system/console/configMgr).
  • sling.servlet.selectors sling.servlet.extensions and  sling.servlet.methods are only considered for the registration with sling.servlet.resourceTypes.
  • All configuration values could be a string or an array of strings (see above example for methods).
  • The default for  sling.servlet.methods are GET and HEAD.

First example will respond to: http://localhost:4502/libs/myservlet

Second example will respond to all pages: http://localhost:4502/content/mypage.mycustomselector.xml

having /apps/myproject/components/mycustomresource as its template component page.

CONCLUSIONS

Registering a Servlet by resource type is the preferred approach in Sling, because request handling is independent of where the resources are located. Therefore, there is no need for a predefined static path.

Only with resource type registration you fully utilize the dynamic, resource-oriented approach of the Sling framework: moreover Sling Engine will take care of permissions for you. Users who cannot access a particular resource will not be able to invoke the servlet.

Last but not least, as for all static path, change it (once you already have specified it to your consumers) will reflect in some other changes or broken behaviors.

AUTHORS

Alessandro Paolinelli, Javier Reyes

BIBLIOGRAPHY

Apache Sling – Servlets and Scripts

Do you want more information?

You Might Also Like

No Comments

    Leave a Reply