I was wondering what best practice would be to bind a servlet to a custom path based on a config. This servlet is an API endpoint, so selectors won't help us too much. For example, I have a servlet at /bin/foo/files, and I'd like to be able to configure that path to be at /bin/bar/files, or even /bar/files, based on an OSGi config or something similar with the path inside.
The best way is still to avoid hardcoding the path in a servlet. I would suggest another approach:
Create sling resource type my/application/api/endpoint1
Write a servlet which handles the POST/GET/... request to that resource type
Build a template which uses my/application/api/endpoint1 as resourcetype OR
Build a component which uses my/application/apo/endpoint as a resourcetype.
Then create a page based on that template or drop the component into a page.
Then you can create, remove, update, duplicate, ... this API endpoint during runtime. You can define ACLs on it (if you require the users of this API to authenticate). You don't need to reconfigure anything on OSGI level.
And you can even create a new "content tree" below /endpoints (who says, that pages can only reside below /content?)
I don't think there's an out of a box way to dynamically set the path of your servlet, however, a solution you can try is to utilise and configure Apache rewrite rules for your use case, PT flag. Have a look at this article, which explains the solution more in detail.
You can try getting it from the query param in servlet as request parameter and then assign it to some servlet's varialble locally. Then while defining the path for the servlet in Java, get this values as <Classname>.<vriableName>