Search code examples
aemsling

AEM/Sling: How do I implement dynamic sling selector?


TLDR: I want setup an AEM page that accepts firstname and lastname as parameter using an SEO friendly URL.

Going to www.host.com/mycontent.richard.williams.html will display information relevant to Richard Williams.

If I go to www.host.com/mycontent.john.smith.html, the page will display information relevant to John Smith.


SEO friendly example: www.host.com/mycontent.richard.williams.html

not SEO friendly example: www.host.com/mycontent.html?firstname=richard&lastname=williams


So I've been following this guide (not sure if this is the best example/guide to help me): http://www.aemcq5tutorials.com/tutorials/sling-servlet-in-aem/

And while it works well for my the example

@SlingServlet(resourceTypes="geometrixx/components/hompepage", selectors={"firstname","lastname"}, extensions="html",methods="GET", metatype=true)

I am trying to make it dynamic.

At the moment, I can only access the servlet if access via: http://localhost:4502/content/geometrixx/en.firstname.lastname.html

I want to make firstname and lastname dynamic parameters/selectors. Like if for example I want to pass the values "richard.williams", I can then use: http://localhost:4502/content/geometrixx/en.richard.williams.html

if I try to use http://localhost:4502/content/geometrixx/en.richard.williams.html right now, I get a blank page.

So basically I want to use selectors for passing parameter values to my page.

Any ideas how this can be done?

ps. At the moment, I only testing/experimenting in my local instance of AEM.


Solution

  • Selectors in sling don't provide the functionality of placing variables in the URL path. i.e. you cannot add {pathParam} like in Spring to sling servlet URL.

    In general, selectors are not recommended to be used like an input to a function. They are to be used more like file extensions. For eg. A request to /mycontent.html returns the same resource as /mycontent.mobile.html. The only difference being, the latter requests for a mobile friendly version.

    Request params on the other hand serve the purpose of providing inputs to the servlet.


    I cannot think of any direct way to attach a servlet to dynamic paths in sling. You can try using suffix, they are cacheable in the dispatcher, but I can't comment on the SEO friendliness of using suffix.

    Consider this URI - /mycontent/user.json/john/smith

    Register a servlet using the path /mycontent/user and you can use String[] names = request.getRequestPathInfo().getSuffix().split(suffix, '/') to retrieve the suffix contents.

    Take a look at answers in this question. Sling ResourceProvider and integrating with jax-rs are other ways you can accomplish this.