Bogdan
Bogdan

Reputation: 412

CQ5 Sling default servlets, same extension but different accepts methods

So I have 2 servlets annotated like this:

@Component
@Service(value = {Servlet.class, NonExistingResourceServlet.class})
@Properties({
    @Property(name = "sling.servlet.resourceTypes",
            value = {"sling/servlet/default"},
            propertyPrivate = true),
    @Property(name = "sling.servlet.extensions",
            value = {"xml"},
            propertyPrivate = true),
    @Property(name = "sling.servlet.methods",
            value = {"GET"},
            propertyPrivate = true))

For both I override the accepts method

@Override
public boolean accepts(SlingHttpServletRequest request) {
    String requestURI = request.getRequestURI();
    if (StringUtils.isNotBlank(requestURI)){
        return requestURI.endsWith("/sevlet1.xml"); //different for the other servlet
    } else {
        return false;
    }
}

IN CQ /system/console/servletresolver one of them is not resolved. Do I have to be more specific in configuration. The accepts method is not enough? Found on Apache Sling doc

If a registered servlet implements the OptingServlet interface, Sling uses that servlet's accepts(SlingHttpServletRequest request) method to refine the servlet resolution process. In this case, the servlet is only selected for processing the current request if its accept method returns true.

For one of them I added a selector and now the difference is made. My question is why do I need to add the selector if I override the accepts method?

The 2 servlets are like this: /content/myapp/sevlet1.xml /content/myapp/sevlet2.xml

Upvotes: 0

Views: 921

Answers (1)

Bertrand Delacretaz
Bertrand Delacretaz

Reputation: 6100

I'm not sure whether the /system/console/servletresolver tool takes OptingServlet into account, you might also put a debugger breakpoint in your accept methods to check that they are actually called when the corresponding HTTP requests come in. Note also that your servlets need to be declared "implements OptingServlet", which I suppose is the case as you have an @Override annotation on your accepts method.

Note that an OptingServlet that checks the request URI is usually not recommended in Sling, dispatching based on resource types or selectors is the recommended best practice.

(edit:) You might also compare your code with the example OptingServlet from the Sling integration tests.

Upvotes: 1

Related Questions