Search code examples
servletsannotationsosgiaem

AEM Servlet not getting executed


I have a servlet with OSGI annotation like below

    @Component( immediate = true, service = Servlet.class, property = { "sling.servlet.extensions=json",
        "sling.servlet.paths=/example/search", "sling.servlet.methods=get" } )
    public class SearchSevrlet
        extends SlingSafeMethodsServlet {
      @Override
        protected void doGet( final SlingHttpServletRequest req, final SlingHttpServletResponse resp )
            throws ServletException, IOException {
      log.info("This is not getting called ");
    }
}

But When i try to hit the servlet with JQuery

$.get( "/example/search.json", function( data ) {
      $( ".result" ).html( data );
      alert( "Load was performed." );
    });

I am getting below information rather than servlet getting executed.

{"sling:resourceSuperType":"sling/bundle/resource","servletClass":"com.group.aem.example.servlet.SearchSevrlet","sling:resourceType":"/example/search.servlet","servletName":"com.group.aem.example.servlet.SearchSevrlet"}

Please let me know if i need to make any other configuration.


Solution

  • The info that you are getting is the answer of the Default JSON Servlet

    Please read this: Servlets and Scripts

    You are registering the "SearchServlet" with the property "sling.servlet.paths". This property is defined as:

    sling.servlet.paths: A list of absolute paths under which the servlet is accessible as a Resource. The property value must either be a single String, an array of Strings...

    That means that your servlet will be only triggered if you request the same exact path, in this case "/example/search", like this:

    GET /example/search
    

    I would recommend you to use the properties "resourceTypes" and "selectors" in your Servlet rather than "paths". For example, a better configuration could be:

        property = { 
            "sling.servlet.resourceTypes=/example/search.servlet",
            "sling.servlet.selectors=searchselector",
            "sling.servlet.extensions=json",
            "sling.servlet.methods=GET" 
        }
    

    With this config, your SearchServlet should be triggered with a GET request to a resource with resourceType="/example/search.servlet", with the selector "searchselector" and the extension "json". For example:

    GET /corcoran/search.searchselector.json